blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
e53a633c0d82fe6d39fa244ae9203ad6305af0e7
Java
marryfeng/goodsdetailcache
/eshop-one-service/src/main/java/com/shop/learning/oneserviceController/OneServiceController.java
UTF-8
1,362
2.296875
2
[]
no_license
package com.shop.learning.oneserviceController; import com.shop.learning.OneServiceService.ProductPriceService; import com.shop.learning.OneServiceService.ProductStockService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; /** * Created by fengli on 2018/3/30. */ @RestController @Api(value = "oneservice服务调用测试") @RequestMapping("/oneservice/") public class OneServiceController { @Autowired private ProductPriceService productPriceService; @Autowired private ProductStockService productStockService; @RequestMapping(value = "price",method = RequestMethod.GET) @ApiOperation(value = "调用价格服务") public String callPrice(@RequestParam(value = "id") Integer id){ return productPriceService.pricecall(id); } @RequestMapping(value = "stock",method = RequestMethod.GET) @ApiOperation(value = "调用库存服务") public String stockPrice(@RequestParam(value = "id") Integer id){ return productStockService.stockcall(id); } }
true
a3361734aef93ad14e9837a970b140fc987853df
Java
DominicBB/ecsGameEngine
/src/util/Mathf/Mathf2D/Vector2D.java
UTF-8
3,300
3.296875
3
[]
no_license
package util.Mathf.Mathf2D; public class Vector2D { public float x; public float y; public float w; public Vector2D(float x, float y) { this.x = x; this.y = y; this.w = 1; } public Vector2D(float x, float y, float w) { this.x = x; this.y = y; this.w = w; } public Vector2D minus(Vector2D other) { return new Vector2D(this.x - other.x, this.y - other.y); } public Vector2D absDiff(Vector2D other) { return new Vector2D(Math.abs(this.x - other.x), Math.abs(this.y - other.y)); } public Vector2D plus(Vector2D other) { return new Vector2D(this.x + other.x, this.y + other.y); } public Vector2D mul(float scaler) { return new Vector2D(this.x * scaler, this.y * scaler); } public void scale(float scaler) { this.x = x * scaler; this.y = y * scaler; } public Vector2D divide(float divider) { return new Vector2D(this.x / divider, this.y / divider); } public float dotProduct(Vector2D other) { return (other.x * other.x) + (other.y * other.x); } public Vector2D unit() { float m = this.magnitude(); return new Vector2D(this.x / m, this.y / m); } public float magnitude() { return (float) Math.sqrt((this.x * this.x) + (this.y * this.y)); } public Vector2D maxValues(Vector2D other) { Vector2D maxValues = Vector2D.newZeros(); maxValues.x = Math.max(x, other.x); maxValues.y = Math.max(y, other.y); return maxValues; } public Vector2D minValues(Vector2D other) { Vector2D minValues = Vector2D.newZeros(); minValues.x = Math.min(x, other.x); minValues.y = Math.min(y, other.y); return minValues; } public float minVal() { float min = x; return Math.min(y, min); } public float maxVal() { float max = x; return Math.max(y, max); } public String toString() { return "[" + x + "," + y + "]"; } public static Vector2D newDown() { return new Vector2D(0f, -1f); } public static Vector2D newUp() { return new Vector2D(0f, 1f); } public static Vector2D newLeft() { return new Vector2D(-1f, 0f); } public static Vector2D newRight() { return new Vector2D(1f, 0f); } public static Vector2D newOnes() { return new Vector2D(1f, 1f); } public static Vector2D newZeros() { return new Vector2D(0f, 0f); } public static final Vector2D ZERO = newZeros(); public void componentAdd(float x, float y) { this.x += x; this.y += y; } public void add(Vector2D other) { this.x += other.x; this.y += other.y; } public void set(float x, float y) { this.x = x; this.y = y; } public void set(Vector2D other) { this.x = other.x; this.y = other.y; } public static void lerp(Vector2D start, Vector2D destination, float lerpAmt) { start.add(destination.minus(start).mul(lerpAmt)); } public Vector2D lerp(Vector2D destination, float lerpAmt) { return destination.minus(this).mul(lerpAmt).plus(this); } }
true
5d091c2cd8bfeba52bd13acb5550d369f0203d2d
Java
KangGilHwan/Shopping-Mall
/src/test/java/riverway/domain/order/OrderItemsTest.java
UTF-8
1,423
2.5625
3
[]
no_license
package riverway.domain.order; import org.junit.Before; import org.junit.Test; import riverway.domain.Coupon; import riverway.domain.User; import riverway.domain.cart.Option; import riverway.domain.cart.Size; import riverway.domain.product.Category; import riverway.domain.product.Product; import java.util.ArrayList; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; public class OrderItemsTest { private OrderItems orderItems; @Before public void setUp() { List<OrderItem> items = new ArrayList<>(); Coupon coupon = new Coupon("2월 쿠폰", 6000); OrderItem item = createOrderitem("흰색 티셔츠", 15000, 1, coupon); items.add(item); item = createOrderitem("양말", 2000, 2, null); items.add(item); orderItems = new OrderItems(items); } @Test public void calculateTotalPrice() { assertThat(orderItems.calculateTotalPrice()).isEqualTo(13000); } @Test public void joinItemNames() { assertThat(orderItems.joinItemNames()).isEqualTo("흰색 티셔츠, 양말"); } public OrderItem createOrderitem(String name, int price, int number, Coupon coupon) { Product product = new Product(name, price, "기본 아이템", Category.MEN, new User()); Option option = new Option(Size.M, number); return new OrderItem(product, option, coupon); } }
true
5eab3cec0a8656d780bee0fc4eb21bdd172b12fc
Java
adamkotkowski/snooker-counter
/src/main/java/com/akotkowski/snooker/Frame.java
UTF-8
17,683
2.359375
2
[ "Apache-2.0" ]
permissive
package com.akotkowski.snooker; import com.akotkowski.snooker.exceptions.FreeBallException; import com.akotkowski.snooker.exceptions.IllegalBallPotted; import com.akotkowski.snooker.model.FrameEventModel; import com.akotkowski.snooker.model.FrameModel; import com.akotkowski.snooker.model.ModelFactory; import com.akotkowski.snooker.model.Player; import com.akotkowski.snooker.model.impl.SimpleModelFactory; import com.akotkowski.snooker.util.PotPossibilities; import com.akotkowski.snooker.util.Util; import java.io.Serializable; import java.util.*; public class Frame implements Serializable { private static final long serialVersionUID = 7344395968895146751L; public static final int FRAME_ENDED = 1; private Match match; Table table = new Table(); FrameModel frameModel; private final ModelFactory modelFactory; public Frame() { this(new SimpleModelFactory().createFrame(), new SimpleModelFactory()); } public Frame(FrameModel frameModel) { this(frameModel, new SimpleModelFactory()); } public Frame(FrameModel frameModel, ModelFactory modelFactory, Match match) { setMatch(match); this.modelFactory = modelFactory; this.frameModel = frameModel; init(); } public Frame(FrameModel frameModel, ModelFactory modelFactory) { this.modelFactory = modelFactory; this.frameModel = frameModel; init(); } private void init(){ if(frameModel!=null && getMatch()!=null){ this.table.setReds(getMatch().getMatch().getReds()); } for (FrameEventModel fe : this.getFrame().getFrameEvents()) { if (fe.getType() == FrameEventModel.Type.BREAK) { if (fe.getBallsPotted() != null) { int i = 0; for (Ball ball : fe.getBallsPotted()) { if (i == 0 && FrameEventHelper.isFreeBall(fe)) continue; this.table.pot(ball); i++; } } } else if (fe.getType() == FrameEventModel.Type.FOUL) { int potCount = fe.getBallsPotted().size(); if (potCount != 0) { this.table.setReds(this.table.getReds() - potCount); } } } this.recalculateScore(); } public Player getWinner() { if (this.getFrame().isCompleted() == false) throw new RuntimeException("Cannot get winner of a frame, that is not completed"); return this.getFrame().getWinner(); } public int getResult(Player player) { return this.getFrame().getResult(player); } public void setResult(Player player, int result) { this.getFrame().setResult(player, result); } public void registerPot(Ball ball, Player player) { if (this.getFrame().isCompleted()) { throw new RuntimeException("Cannot pot in completed frame"); } FrameEventModel event = getlastEvent(); if (this.table.getReds() == 0 && event != null) { event.setInColors(true); } if (event != null && event.getType() == FrameEventModel.Type.BREAK && event.isOpen() && event.getPlayerScored() == player) { // add pot to the current break FrameEventHelper.pot(this.getlastEvent(), ball); } else { if (this.getlastEvent() != null && this.getlastEvent().getType() == FrameEventModel.Type.BREAK) FrameEventHelper.setOpen(this.getlastEvent(), false); // start new brake FrameEventModel t = modelFactory.createFrameEvent(); t.setPlayerScored(player); FrameEventHelper.pot(t, ball); t.setFrame(this.getFrame()); t.setType(FrameEventModel.Type.BREAK); t.setOpen(true); if (this.table.getReds() == 0) { t.setInColors(true); } List<FrameEventModel> l = (List<FrameEventModel>) this.getFrame().getFrameEvents(); l.add(t); } this.table.pot(ball); // FIX for: // if someone pots last red ball, than pots yellow, then Table will set next color to green, which is bad behavior (it should be yellow) List<Ball> ballsPotted = this.getlastEvent().getBallsPotted(); int ballsPottedSize = ballsPotted.size(); if (ballsPottedSize > 1 && ballsPotted.get(ballsPottedSize - 1) == Ball.YELLOW && ballsPotted.get(ballsPottedSize - 2) == Ball.RED && this.table.getColorRemained() == Ball.GREEN) { table.setColorRemained(Ball.YELLOW); } // END of FIX this.recalculateScore(); if (this.table.isCleared()) { if (this.getResult(Player.ONE) != this.getResult(Player.TWO)) { if (this.getlastEvent().getType() == FrameEventModel.Type.BREAK) FrameEventHelper.setOpen(this.getlastEvent(), false); this.getFrame().setCompleted(true); calculateWinner(); this.match.onFrameCompleted(); } else { // fight for the black if (this.getlastEvent().getType() == FrameEventModel.Type.BREAK) FrameEventHelper.setOpen(this.getlastEvent(), false); table.setColorRemained(Ball.BLACK); } } } public void registerFreeBall(Ball ball, Player player) { if (this.getFrame().isCompleted()) { throw new IllegalBallPotted(ball, "Cannot pot in ended frame"); } FrameEventModel lastEvent = this.getlastEvent(); if (lastEvent == null) { throw new FreeBallException("Free ball cannot be potted without any foul"); } FrameEventModel event = getlastEvent(); if (lastEvent.getType() != FrameEventModel.Type.FOUL || lastEvent.getPlayerScored() != player) { throw new FreeBallException("Free ball cannot be potted by player who commited the foul"); } // start new brake FrameEventModel t = modelFactory.createFrameEvent(); t.setPlayerScored(player); FrameEventHelper.pot(t, ball); t.setType(FrameEventModel.Type.BREAK); t.setOpen(true); if (this.getTable().getReds() > 0) { t.setScore(1); t.setFreeBallScore(1); } else { t.setScore(this.getTable().getColorRemained().getValue()); t.setFreeBallScore(this.getTable().getColorRemained().getValue()); } List<FrameEventModel> l = (List<FrameEventModel>) this.getFrame().getFrameEvents(); t.setFrame(this.getFrame()); l.add(t); if (this.table.getReds() == 0) { this.getlastEvent().setInColors(true); } this.recalculateScore(); } public void registerMultipleRedPot(int i, Player player) { if (i > table.getReds()) { return; //throw new RuntimeException("Not enough reds on the table."); } if (this.getFrame().isCompleted()) { throw new RuntimeException("Cannot pot in ended frame"); } FrameEventModel event = getlastEvent(); if (event != null && event.getType() == FrameEventModel.Type.BREAK && event.isOpen() && event.getPlayerScored() == player) { // add pot to the current break FrameEventHelper.potReds(this.getlastEvent(), i); } else { if (this.getlastEvent() != null && this.getlastEvent().getType() == FrameEventModel.Type.BREAK) FrameEventHelper.setOpen(this.getlastEvent(), false); // start new brake FrameEventModel t = modelFactory.createFrameEvent(); t.setPlayerScored(player); t.setType(FrameEventModel.Type.BREAK); FrameEventHelper.potReds(t, i); List<FrameEventModel> l = (List<FrameEventModel>) this.getFrame().getFrameEvents(); t.setFrame(this.getFrame()); l.add(t); } for (int k = 0; k < i; k++) this.table.pot(Ball.RED); this.recalculateScore(); } public void registerMiss() { if (this.getlastEvent() != null && this.getlastEvent().getType() == FrameEventModel.Type.BREAK) FrameEventHelper.setOpen(this.getlastEvent(), false); if ((this.table.isOnlyBlackOnTheTable() && Math.abs(this.getResult(Player.ONE) - this.getResult(Player.TWO)) > 7) || this.table.isCleared()) { this.getFrame().setCompleted(true); calculateWinner(); this.match.onFrameCompleted(); } } public FrameEventModel getlastEvent() { if (this.getFrame().getFrameEvents().size() == 0) return null; return this.getFrame().getFrameEvents().get(this.getFrame().getFrameEvents().size() - 1); } public void registerFaul(Ball ball, Player player, int reds) { List<FrameEventModel> l = (List<FrameEventModel>) this.getFrame().getFrameEvents(); FrameEventModel event = modelFactory.createFrameEvent(); event.setPlayerScored(player.getOponent()); event.setScore(ball.getValue() < 4 ? 4 : ball.getValue()); event.setType(FrameEventModel.Type.FOUL); int redsOnTable = table.getReds(); redsOnTable -= reds; if (redsOnTable < 0) { reds += redsOnTable; redsOnTable = 0; } for (int m = 0; m < reds; m++) { FrameEventHelper.addBallPoted(event, Ball.RED); } table.setReds(redsOnTable); event.setFrame(this.getFrame()); l.add(event); this.recalculateScore(); } private void recalculateScore() { Map<Player, Integer> results = new HashMap<Player, Integer>(); for (FrameEventModel e : this.getFrame().getFrameEvents()) { results.put(e.getPlayerScored(), Util.getOrDefault(results, e.getPlayerScored(), 0) + e.getScore()); } this.getFrame().setResult(Player.ONE, Util.getOrDefault(results, Player.ONE, 0)); this.getFrame().setResult(Player.TWO, Util.getOrDefault(results, Player.TWO, 0)); } public Table getTable() { return table; } public void setTable(Table table) { this.table = table; } public void registerRetire(Player player) { this.getFrame().setCompleted(true); FrameEventModel fe = modelFactory.createFrameEvent(); fe.setPlayerScored(player); fe.setType(FrameEventModel.Type.FRAME_SURRENDER); fe.setDate(new Date()); List<FrameEventModel> lst = (List<FrameEventModel>) this.getFrame().getFrameEvents(); fe.setFrame(this.getFrame()); lst.add(fe); this.getFrame().setWinner(player.getOponent()); this.getFrame().setCompleted(true); this.recalculateScore(); this.match.onFrameCompleted(); } private void calculateWinner() { if (this.getFrame().isCompleted()) { if (this.getFrame().getResult(Player.ONE) > this.getFrame().getResult(Player.TWO)) { this.getFrame().setWinner(Player.ONE); } else { this.getFrame().setWinner(Player.TWO); } } } public Match getMatch() { return match; } public void resign(Player player) { this.getFrame().setWinner(player); this.getFrame().setCompleted(true); this.match.onFrameCompleted(); } public void setMatch(Match match) { this.match = match; } public static List<FrameEventModel> getBreaks(FrameModel frame) { ArrayList<FrameEventModel> ret = new ArrayList<FrameEventModel>(); for (FrameEventModel fe : frame.getFrameEvents()) { if (fe.getType().equals(FrameEventModel.Type.BREAK.name)) ret.add(fe); } return ret; } public PotPossibilities getPotPossiibilities(Player player) { FrameEventModel ev = this.getlastEvent(); if (ev != null && ev.getType() == FrameEventModel.Type.BREAK) { if (ev.getPlayerScored() == player) { if (FrameEventHelper.isFreeBall(ev) && ev.getBallsPottedCount() == 1) { if (table.getReds() > 0) { return PotPossibilities.COLOR; } else { return new PotPossibilities(this.table.getColorRemained()); } } Ball lastPot = FrameEventHelper.getLastPot(ev); if (ev.isOpen() && ev.isInColors() && this.table.getReds() == 0 && lastPot!=null && lastPot.getType() == Ball.Type.COLOR) { return new PotPossibilities(this.table.getColorRemained()); } else if (FrameEventHelper.isOpen(ev) && lastPot!=null && lastPot.getType() == Ball.Type.COLOR && !(ev.getScore() == 1 && FrameEventHelper.isFreeBall(ev))) { return PotPossibilities.RED; } else if (FrameEventHelper.isOpen(ev) && (lastPot!=null && lastPot.getType() == Ball.Type.RED || (ev.getScore() == 1 && FrameEventHelper.isFreeBall(ev)))) { return PotPossibilities.COLOR; } else if (!FrameEventHelper.isOpen(ev) && this.table.getReds() == 0) { return new PotPossibilities(this.table.getColorRemained()); } } } if (this.table.getReds() == 0) { return new PotPossibilities(this.table.getColorRemained()); } return PotPossibilities.RED; } public int getBehind() { return Math.abs(this.getResult(Player.ONE) - this.getResult(Player.TWO)); } public int getRemaining() { int ret = this.table.getReds() * 8; Ball lastPotted = null; FrameEventModel lastEvent = this.getlastEvent(); if (lastEvent != null && lastEvent.getBallsPotted().size() > 0) { lastPotted = this.getlastEvent().getBallsPotted().get(this.getlastEvent().getBallsPotted().size() - 1); } if (lastEvent != null && lastEvent.getType() == FrameEventModel.Type.BREAK && this.getlastEvent().isOpen() && lastPotted == Ball.RED) ret += 7; if (ret > 0) { ret += 27; } else { if (this.table != null && this.table.getColorRemained() != null) for (int i = 7; i >= this.table.getColorRemained().getValue(); i--) { ret += i; } } return ret; } public int getCurrentBreak(Player player) { if (this.getlastEvent() == null || this.getlastEvent().getType() != FrameEventModel.Type.BREAK || !this.getlastEvent().isOpen() || this.getlastEvent().getPlayerScored() != player) return 0; return this.getlastEvent().getScore(); } public boolean undo() { if (this.getFrame().isCompleted()) { this.getFrame().setCompleted(false); } if (this.getFrame().getFrameEvents() != null && this.getFrame().getFrameEvents().size() > 0) { if (this.getlastEvent() != null) { if (this.getlastEvent().getType() == FrameEventModel.Type.BREAK) { if (this.getlastEvent().isOpen()) { Ball ball = FrameEventHelper.removeLastPot(this.getlastEvent()); if (this.getlastEvent().getBallsPotted() == null || this.getlastEvent().getBallsPotted().isEmpty()) { FrameEventModel toDelete = this.getlastEvent(); modelFactory.removeFrameEvent(this.getlastEvent()); this.getFrame().getFrameEvents().remove(this.getFrame().getFrameEvents().size() - 1); } if (ball == Ball.RED) { this.table.setReds(this.table.getReds() + 1); } else if (this.table.getReds() == 0 && this.table.getColorRemained()!=null && this.table.getColorRemained().getValue() == ball.getValue() + 1) { this.table.setColorRemained(ball); } else if (this.table.getReds() == 0 && ball.getType() == Ball.Type.COLOR) { this.getlastEvent().setInColors(false); } } else { this.getlastEvent().setOpen(true); } } else { int potCount = this.getlastEvent().getBallsPotted().size(); if (this.getlastEvent().getType() == FrameEventModel.Type.FOUL && potCount != 0) { this.table.setReds(this.table.getReds() + potCount); } modelFactory.removeFrameEvent(this.getlastEvent()); this.getFrame().getFrameEvents().remove(this.getFrame().getFrameEvents().size() - 1); } } this.recalculateScore(); return true; } return false; } public FrameModel getFrame() { return this.frameModel; } public void setFrame(FrameModel frame) { this.frameModel = frame; } public List<Ball> getCurrentBreakBalls(Player player) { FrameEventModel fem = getlastEvent(); if (fem != null && fem.getPlayerScored() == player && fem.getType() == FrameEventModel.Type.BREAK && fem.isOpen()) return fem.getBallsPotted(); return new ArrayList<Ball>(); } }
true
a355e5d584ade98efd5b98899508d380bdbe67fc
Java
ruchiraavsv/PriceCalculator
/src/test/java/com/price/calculator/v1/repository/ItemRepositoryTest.java
UTF-8
2,518
2.234375
2
[]
no_license
package com.price.calculator.v1.repository; import com.price.calculator.v1.constants.AppConstants; import com.price.calculator.v1.constants.TestConstants; import com.price.calculator.v1.model.Item; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit.jupiter.SpringExtension; @ExtendWith(SpringExtension.class) @DataJpaTest @ActiveProfiles(profiles = "test") class ItemRepositoryTest { @Autowired ItemRepository itemRepository; @BeforeEach public void setUp() { itemRepository.deleteAll(); itemRepository.save(new Item(1, AppConstants.PENGUINEAR, TestConstants.penguinEar_carton_size, TestConstants.penguinEar_carton_price)); } @Test void testFindItemByName() { Item item = itemRepository.findByName(AppConstants.PENGUINEAR).get(); Assertions.assertEquals(TestConstants.penguinEar_carton_size,item.getCartonSize()); Assertions.assertEquals(TestConstants.penguinEar_carton_price,item.getCartonPrice()); } @Test void tesCreateItem() { Item item = new Item(2, AppConstants.HORSESHOE, TestConstants.horseShoe_carton_size, TestConstants.horseShoe_carton_price); Item itemSaved = itemRepository.save(item); Assertions.assertTrue(itemRepository.existsById(item.getId())); Assertions.assertEquals(item.getId(), itemSaved.getId()); Assertions.assertEquals(item.getCartonSize(), itemSaved.getCartonSize()); Assertions.assertEquals(item.getCartonPrice(), itemSaved.getCartonPrice()); } @Test void tesUpdateItem() { Item item = new Item(2, AppConstants.HORSESHOE, TestConstants.horseShoe_carton_size, TestConstants.horseShoe_carton_price); itemRepository.save(item); item.setCartonPrice(200); Item itemUpdated = itemRepository.save(item); Assertions.assertEquals(item.getCartonPrice(), 200); } @Test void tesDeleteItem() { int id = itemRepository.findByName(AppConstants.PENGUINEAR).get().getId(); Assertions.assertTrue(itemRepository.existsById(id)); itemRepository.deleteById(id); Assertions.assertFalse(itemRepository.existsById(id)); } }
true
bd91620d4178dbf57bebab358db9ad4268a4a11d
Java
Jikoo/BookSuite
/src/main/java/com/github/jikoo/booksuite/update/UpdateStrings.java
UTF-8
1,545
2.578125
3
[]
no_license
/** * */ package com.github.jikoo.booksuite.update; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Set; import org.bukkit.configuration.file.YamlConfiguration; import com.github.jikoo.booksuite.BookSuite; /** * @author Jikoo * */ public class UpdateStrings { private BookSuite plugin; public UpdateStrings(BookSuite plugin) { this.plugin = plugin; } public boolean update() { YamlConfiguration strings = YamlConfiguration.loadConfiguration(new File(plugin.getDataFolder(), "strings.yml")); InputStream stream = plugin.getResource("strings.yml"); InputStreamReader reader = new InputStreamReader(stream); YamlConfiguration defaultStrings = YamlConfiguration.loadConfiguration(reader); try { stream.close(); reader.close(); } catch (IOException e) { System.err.println("Unable to close streams while reading default config!"); } Set<String> options = defaultStrings.getKeys(false); Set<String> current = strings.getKeys(false); boolean changed = false; for (String s : options) { if (!current.contains(s)) { strings.set(s, defaultStrings.get(s)); changed = true; } } for (String s : current) { if (!options.contains(s)) { strings.set(s, null); changed = true; } } strings.options().copyHeader(true); if (changed) { try { strings.save(new File(plugin.getDataFolder(), "strings.yml")); } catch (Exception e) { e.printStackTrace(); } } return changed; } }
true
6467c15a4a980daba356a0dbaf449a3008078e1c
Java
andyradz/codigo.aplios
/domain/domain-model/src/main/java/com/codigo/aplios/domain/model/calendar/Calendar.java
UTF-8
1,332
2.46875
2
[]
no_license
package com.codigo.aplios.domain.model.calendar; import java.io.Serializable; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.OneToOne; import javax.persistence.Table; @Entity @Table(name = "Calendar") public class Calendar implements Serializable { private static final long serialVersionUID = 7149137451110949342L; @EmbeddedId private CalendarPrimaryKey calendarPrimaryKey; @Column(name = "Name", length = 50, nullable = false, unique = true) private String name; public Calendar() { } public Calendar(final CalendarPrimaryKey calendarPrimaryKey) { this.calendarPrimaryKey = calendarPrimaryKey; } @OneToOne(optional = false, mappedBy = "calendar", cascade = CascadeType.PERSIST) private CalendarDay calendarDay; public String getName() { return this.name; } public void setName(final String name) { this.name = name; } public CalendarDay getCalendarDay() { return this.calendarDay; } public void setCalendarDay(final CalendarDay calendarDay) { this.calendarDay = calendarDay; } @Override public String toString() { return "Calendar [calendarPrimaryKey=" + this.calendarPrimaryKey + ", name=" + this.name + ", calendarDay=" + this.calendarDay + "]"; } }
true
a7dbaa7cbaac9bed8efd1f10236eb5cbc37c4570
Java
sid2709/Mockito
/Mockito/src/test/java/com/mockito/Mockito/SomeBussinessMockTest2.java
UTF-8
933
2.5
2
[]
no_license
package com.mockito.Mockito; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import org.junit.jupiter.api.Test; class SomeBussinessMockTest2 { @Test public void testFindTheGreatestOfAllData() { DataService dataServiceMock = mock(DataService.class); when(dataServiceMock.retrieveAllData()).thenReturn(new int[] {24,15,3}); SomeBussinessImpl bussinessImpl = new SomeBussinessImpl(dataServiceMock); int result = bussinessImpl.findTheGreatestFromAllData(); assertEquals(24, result); } @Test public void testFindTheGreatestOfAllData2() { DataService dataServiceMock = mock(DataService.class); when(dataServiceMock.retrieveAllData()).thenReturn(new int[] {14}); SomeBussinessImpl bussinessImpl = new SomeBussinessImpl(dataServiceMock); int result = bussinessImpl.findTheGreatestFromAllData(); assertEquals(14, result); } }
true
e1e3c899a3ac8cb5f67496a0ed813beb35d2dc04
Java
confluentinc/kafka
/metadata/src/test/java/org/apache/kafka/image/DelegationTokenImageTest.java
UTF-8
6,594
1.765625
2
[ "Apache-2.0", "GPL-2.0-only", "LicenseRef-scancode-public-domain", "W3C", "CC0-1.0", "GPL-1.0-or-later", "CPL-1.0", "GPL-2.0-or-later", "LicenseRef-scancode-generic-export-compliance", "LicenseRef-scancode-other-permissive", "CC-PDDC", "BSD-3-Clause", "APSL-2.0", "LicenseRef-scancode-free-unknown", "EPL-2.0", "CDDL-1.0", "MIT", "LicenseRef-scancode-unknown-license-reference", "EPL-1.0", "Classpath-exception-2.0", "CDDL-1.1", "BSD-2-Clause", "WTFPL" ]
permissive
/* * 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 * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kafka.image; import org.apache.kafka.common.metadata.DelegationTokenRecord; import org.apache.kafka.common.metadata.RemoveDelegationTokenRecord; import org.apache.kafka.common.security.auth.KafkaPrincipal; import org.apache.kafka.common.security.token.delegation.TokenInformation; import org.apache.kafka.common.utils.SecurityUtils; import org.apache.kafka.image.writer.ImageWriterOptions; import org.apache.kafka.image.writer.RecordListWriter; import org.apache.kafka.metadata.RecordTestUtils; import org.apache.kafka.metadata.DelegationTokenData; import org.apache.kafka.server.common.ApiMessageAndVersion; import org.apache.kafka.server.common.MetadataVersion; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.fail; @Timeout(value = 40) public class DelegationTokenImageTest { public final static DelegationTokenImage IMAGE1; public final static List<ApiMessageAndVersion> DELTA1_RECORDS; final static DelegationTokenDelta DELTA1; final static DelegationTokenImage IMAGE2; static DelegationTokenData randomDelegationTokenData(String tokenId, long expireTimestamp) { TokenInformation ti = new TokenInformation( tokenId, SecurityUtils.parseKafkaPrincipal(KafkaPrincipal.USER_TYPE + ":" + "fred"), SecurityUtils.parseKafkaPrincipal(KafkaPrincipal.USER_TYPE + ":" + "fred"), new ArrayList<KafkaPrincipal>(), 0, 1000, expireTimestamp); return new DelegationTokenData(ti); } static { Map<String, DelegationTokenData> image1 = new HashMap<>(); image1.put("somerandomuuid1", randomDelegationTokenData("somerandomuuid1", 100)); image1.put("somerandomuuid2", randomDelegationTokenData("somerandomuuid2", 100)); image1.put("somerandomuuid3", randomDelegationTokenData("somerandomuuid3", 100)); IMAGE1 = new DelegationTokenImage(image1); DELTA1_RECORDS = new ArrayList<>(); DELTA1_RECORDS.add(new ApiMessageAndVersion(new DelegationTokenRecord(). setOwner(KafkaPrincipal.USER_TYPE + ":" + "fred"). setRequester(KafkaPrincipal.USER_TYPE + ":" + "fred"). setIssueTimestamp(0). setMaxTimestamp(1000). setExpirationTimestamp(200). setTokenId("somerandomuuid1"), (short) 0)); DELTA1_RECORDS.add(new ApiMessageAndVersion(new RemoveDelegationTokenRecord(). setTokenId("somerandomuuid3"), (short) 0)); DELTA1 = new DelegationTokenDelta(IMAGE1); RecordTestUtils.replayAll(DELTA1, DELTA1_RECORDS); Map<String, DelegationTokenData> image2 = new HashMap<>(); image2.put("somerandomuuid1", randomDelegationTokenData("somerandomuuid1", 200)); image2.put("somerandomuuid2", randomDelegationTokenData("somerandomuuid2", 100)); IMAGE2 = new DelegationTokenImage(image2); } @Test public void testEmptyImageRoundTrip() throws Throwable { testToImage(DelegationTokenImage.EMPTY); } @Test public void testImage1RoundTrip() throws Throwable { testToImage(IMAGE1); } @Test public void testApplyDelta1() throws Throwable { assertEquals(IMAGE2, DELTA1.apply()); // check image1 + delta1 = image2, since records for image1 + delta1 might differ from records from image2 List<ApiMessageAndVersion> records = getImageRecords(IMAGE1); records.addAll(DELTA1_RECORDS); testToImage(IMAGE2, records); } @Test public void testImage2RoundTrip() throws Throwable { // testToImageAndBack(IMAGE2); testToImage(IMAGE2); } private static void testToImage(DelegationTokenImage image) { testToImage(image, Optional.empty()); } private static void testToImage(DelegationTokenImage image, Optional<List<ApiMessageAndVersion>> fromRecords) { testToImage(image, fromRecords.orElseGet(() -> getImageRecords(image))); } private static void testToImage(DelegationTokenImage image, List<ApiMessageAndVersion> fromRecords) { // test from empty image stopping each of the various intermediate images along the way new RecordTestUtils.TestThroughAllIntermediateImagesLeadingToFinalImageHelper<>( () -> DelegationTokenImage.EMPTY, DelegationTokenDelta::new ).test(image, fromRecords); } private static List<ApiMessageAndVersion> getImageRecords(DelegationTokenImage image) { RecordListWriter writer = new RecordListWriter(); image.write(writer, new ImageWriterOptions.Builder().build()); return writer.records(); } @Test public void testEmptyWithInvalidIBP() { ImageWriterOptions imageWriterOptions = new ImageWriterOptions.Builder(). setMetadataVersion(MetadataVersion.IBP_3_5_IV2).build(); RecordListWriter writer = new RecordListWriter(); DelegationTokenImage.EMPTY.write(writer, imageWriterOptions); } @Test public void testImage1withInvalidIBP() { ImageWriterOptions imageWriterOptions = new ImageWriterOptions.Builder(). setMetadataVersion(MetadataVersion.IBP_3_5_IV2).build(); RecordListWriter writer = new RecordListWriter(); try { IMAGE1.write(writer, imageWriterOptions); fail("expected exception writing IMAGE with Delegation Token records for MetadataVersion.IBP_3_5_IV2"); } catch (Exception expected) { // ignore, expected } } }
true
9307bd89416b453ddff375a344317d211c7c29da
Java
rcarreraamoedo/Singleton
/singletonprueba/SingletonPrueba.java
UTF-8
634
2.96875
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package singletonprueba; /** * * @author usuario */ public class SingletonPrueba { /** * @param args the command line arguments */ public static void main(String[] args) { Persona obx1= Persona.getInstance("Pepe", 34, "Guerrero"); Persona obx2=Persona.getInstance("Roberto",36,"DosSantos"); System.out.println(obx1.getNombre()); System.out.println(obx2.getNombre()); } }
true
e4f1d20241541aee7693a112f30718401aa60ea3
Java
bellmit/myprojects
/js-school-port/src/com/hikootech/mqcash/web/BaseController.java
UTF-8
2,580
2.28125
2
[]
no_license
package com.hikootech.mqcash.web; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import com.hikootech.mqcash.po.UserInfo; import com.hikootech.mqcash.util.IdentifyingCode; import com.hikootech.mqcash.util.Page; import com.hikootech.mqcash.util.UserUtils; /** * 2014年1月16日 * com.jiexun.pos.webBaseController.java * @author yuwei * 基控制器 */ public class BaseController { @Autowired private HttpServletRequest request; protected Page pv ; public BaseController() { } public UserInfo getUserInfo(){ UserInfo userInfo = UserUtils.getUserInfoFromCache(getRequest().getSession()); return userInfo; } public HttpServletRequest getRequest() { return request; } /** * 根据请求总页数,初始化分页VO * @param total */ public void initPV(int total){ //这里取得每页显示条数,以及当前请求页数 String pageNo = request.getParameter("start") ;// 当前页数 int pageSize = Page.PAGESIZE;// 每页大小 int pageNoInt=1; try { pageNoInt=Integer.parseInt(pageNo); } catch (Exception e) { // TODO: handle exception } pv = new Page(pageSize, pageNoInt, total); } public Page getPv() { return pv; } public void setPv(Page pv) { this.pv = pv; } /**constructValidationCode * 此方法描述的是:生成验证码的函数 * @author: zhaohefei * @version: 2015年10月17日 下午2:56:33 */ public List<Object> constructValidationCode(){ IdentifyingCode idCode = new IdentifyingCode(); BufferedImage image = new BufferedImage(idCode.getWidth(), idCode.getHeight(), BufferedImage.TYPE_INT_BGR); Graphics2D g = image.createGraphics(); // 定义字体样式 Font myFont = new Font("行楷", Font.ITALIC, 22); // 设置字体 g.setFont(myFont); // g.setColor(idCode.getRandomColor(200, 250)); // // 绘制背景 // g.fillRect(0, 0, idCode.getWidth(), idCode.getHeight()); // // g.setColor(idCode.getRandomColor(180, 200)); // idCode.drawRandomLines(g, 160); g.setColor(Color.WHITE); // 绘制背景 g.fillRect(0, 0, idCode.getWidth(), idCode.getHeight()); g.setColor(Color.WHITE); idCode.drawRandomLines(g, 0); String validationCode = idCode.drawRandomString(4, g); g.dispose(); List<Object> list=new ArrayList<Object>(); list.add(validationCode); list.add(image); return list; } }
true
c2abe37ea971f880481cc46a05e299a838efd6a8
Java
morristech/Android-DentalManager
/app/src/main/java/za/co/morristech/dentalmanager/app/provider/AbstractDataProvider.java
UTF-8
223
1.71875
2
[]
no_license
package za.co.morristech.dentalmanager.app.provider; /** * Created by wademorris on 2014/09/10. */ public abstract class AbstractDataProvider { //TODO Complete this abstract class for all data providers to extend. }
true
a7dd6921c2762adf350a3f2a8b6c631af43156bd
Java
group-18/terning
/test/terning/DiceTest.java
UTF-8
2,064
3.09375
3
[]
no_license
package terning; import terning.Dice; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; import static org.hamcrest.CoreMatchers.*; public class DiceTest { private Dice d1; @Before public void setUp() throws Exception { this.d1 = new Dice(); } @After public void tearDown() throws Exception { } @Test public void roll() throws Exception { int result = this.d1.roll(); assertTrue("Terningen er mindre end 1", result >= 1); assertTrue("Terningen er større end 6", result <= 6); } @Test public void rollMultiple() throws Exception { int one = 0; int two = 0; int three = 0; int four = 0; int five = 0; int six = 0; for (int i = 0; i < 60000; i++) { int result = this.d1.roll(); switch(result) { case 1: one++; break; case 2: two++; break; case 3: three++; break; case 4: four++; break; case 5: five++; break; case 6: six++; break; } } assertTrue("Der er for få 1'er " + one, one > 9600); assertTrue("Der er for mange 1'er " + one, one < 10400); assertTrue("Der er for få 2'er " + two, two > 9600); assertTrue("Der er for mange 2'er " + two, two < 10400); assertTrue("Der er for få 3'er " + three, three > 9600); assertTrue("Der er for mange 3'er " + three, three < 10400); assertTrue("Der er for få 4'er " + four, four > 9600); assertTrue("Der er for mange 4'er " + four, four < 10400); assertTrue("Der er for få 5'er " + five, five > 9600); assertTrue("Der er for mange 5'er " + five, five < 10400); assertTrue("Der er for få 6'er " + six, six > 9600); assertTrue("Der er for mange 6'er " + six, six < 10400); } }
true
4f3d963ff0caa12028a01689d33bf4bb3b9cf63e
Java
FEFJay/myproject
/WeiboHot/src/DBManager.java
UTF-8
1,716
2.625
3
[]
no_license
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; public class DBManager { // 创建静态全局变量 static Connection conn; static Statement st; static String tmp;//插入微博的内容的时候的缓存变量 public static void main (String args[]){ } /* 获取数据库连接的函数*/ public static Connection getConnection() { Connection con = null; //创建用于连接数据库的Connection对象 try { Class.forName("com.mysql.jdbc.Driver");// 加载Mysql数据驱动 con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/weibo_hot", "root", "123456");// 创建数据连接 } catch (Exception e) { e.printStackTrace(); System.out.println("数据库连接失败" + e.getMessage()); } return con; //返回所建立的数据库连接 } public static int insertWeiboHotContent(String tableName,String date,String url,String weibo_content) { int count = 0; try { conn = getConnection(); String sqlString = "insert into "+tableName+"(time,url,weibo_content) values (?,?,?)"; PreparedStatement pst = conn.prepareStatement(sqlString); pst.setString(1, date); pst.setString(2, url); pst.setString(3, weibo_content); count = pst.executeUpdate(); pst.close(); conn.close(); } catch (Exception e) { System.out.println("数据库插入异常!"+e.getMessage()); } return count; } }
true
a7fe1f46af6a1a63108a524ec02fa4a6ec5fde85
Java
AlexNikolich/Sample-spring-boot
/final-soap-project/src/main/java/com/senecasoap/soap/factory/SaleSoap.java
UTF-8
4,186
1.953125
2
[]
no_license
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.7 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2018.04.04 at 04:45:59 PM PDT // package com.senecasoap.soap.factory; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for SaleSoap complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="SaleSoap"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="customer" type="{http://www.senecasoap.com/soap/factory}CustomerSoap"/> * &lt;element name="product" type="{http://www.senecasoap.com/soap/factory}ProductSoap"/> * &lt;element name="salesRep" type="{http://www.senecasoap.com/soap/factory}SalesRepSoap"/> * &lt;element name="time" type="{http://www.senecasoap.com/soap/factory}TimeSoap"/> * &lt;element name="salesAmount" type="{http://www.w3.org/2001/XMLSchema}double"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "SaleSoap", propOrder = { "customer", "product", "salesRep", "time", "salesAmount" }) public class SaleSoap { @XmlElement(required = true) protected CustomerSoap customer; @XmlElement(required = true) protected ProductSoap product; @XmlElement(required = true) protected SalesRepSoap salesRep; @XmlElement(required = true) protected TimeSoap time; protected double salesAmount; /** * Gets the value of the customer property. * * @return * possible object is * {@link CustomerSoap } * */ public CustomerSoap getCustomer() { return customer; } /** * Sets the value of the customer property. * * @param value * allowed object is * {@link CustomerSoap } * */ public void setCustomer(CustomerSoap value) { this.customer = value; } /** * Gets the value of the product property. * * @return * possible object is * {@link ProductSoap } * */ public ProductSoap getProduct() { return product; } /** * Sets the value of the product property. * * @param value * allowed object is * {@link ProductSoap } * */ public void setProduct(ProductSoap value) { this.product = value; } /** * Gets the value of the salesRep property. * * @return * possible object is * {@link SalesRepSoap } * */ public SalesRepSoap getSalesRep() { return salesRep; } /** * Sets the value of the salesRep property. * * @param value * allowed object is * {@link SalesRepSoap } * */ public void setSalesRep(SalesRepSoap value) { this.salesRep = value; } /** * Gets the value of the time property. * * @return * possible object is * {@link TimeSoap } * */ public TimeSoap getTime() { return time; } /** * Sets the value of the time property. * * @param value * allowed object is * {@link TimeSoap } * */ public void setTime(TimeSoap value) { this.time = value; } /** * Gets the value of the salesAmount property. * */ public double getSalesAmount() { return salesAmount; } /** * Sets the value of the salesAmount property. * */ public void setSalesAmount(double value) { this.salesAmount = value; } }
true
7987fdf7f84ad3dbd8c8ddb2c859261d9b6c6461
Java
Jeroen123TC/NewAmazingLuckyBlocks
/src/net/servermc/plugins/Listeners/Objets/DarkHole.java
UTF-8
5,536
1.96875
2
[ "MIT" ]
permissive
package net.servermc.plugins.Listeners.Objets; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.UUID; import net.servermc.plugins.AmazingLuckyBlocks; import net.servermc.plugins.utils.CLBManager; import net.servermc.plugins.utils.LangLoader; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.EquipmentSlot; import net.servermc.plugins.utils.WorldList; import net.servermc.plugins.utils.Timer; import org.bukkit.scheduler.BukkitScheduler; public class DarkHole implements Listener { HashSet<Material> transparent = new HashSet(); private AmazingLuckyBlocks plugin; public DarkHole(AmazingLuckyBlocks plugin){ this.plugin = plugin; } public String color(String str) { return ChatColor.translateAlternateColorCodes('&', str); } int taskID; int bloques = CLBManager.getManager().getConfig().getInt("Objects.DarkHole.number-of-blocks"); long ticks = CLBManager.getManager().getConfig().getInt("Objects.DarkHole.time-between-one-block-and-the-next"); @EventHandler /*public void ejecucion(PlayerInteractEvent lightning){ Player player = lightning.getPlayer(); BukkitScheduler sh = Bukkit.getServer().getScheduler(); taskID = sh.scheduleSyncRepeatingTask(plugin,new Runnable(){ public void run(){ if(tiempo == 0){ player.sendMessage("Tiempo agotado"); return; }else{ player.sendMessage("Bloque colocado"); tiempo--; //tambien se puede poner tiempo = tiempo -1; } } },0L,20); }*/ public void regenInteraction(PlayerInteractEvent dark) { Player player = dark.getPlayer(); Action action = dark.getAction(); String darkName = color(LangLoader.LangCfg.getString("Objects.DarkHole.name")); if(!AmazingLuckyBlocks.instance.minecraftVersion.equals("1.8")){ if(dark.getHand() == EquipmentSlot.OFF_HAND){ return; } } if ((action.equals(Action.RIGHT_CLICK_BLOCK)) && (player.getItemInHand().getType() == Material.valueOf(CLBManager.getManager().getConfig().getString("Objects.DarkHole.block-material")))) { ItemStack stack = player.getItemInHand(); if (!WorldList.instance.worlds.contains(player.getWorld().getName())) { return; } if ((CLBManager.getManager().getConfig().getBoolean("Objects.DarkHole.required-permission")) && (!player.hasPermission(CLBManager.getManager().getConfig().getString("Objects.DarkHole.permission")))) { player.sendMessage(color(LangLoader.LangCfg.getString("need-permission"))); return; } if ((stack.hasItemMeta()) && (stack.getItemMeta().getDisplayName().equals(darkName))) { this.transparent.add(Material.AIR); Block block; if(AmazingLuckyBlocks.instance.minecraftVersion.equals("1.13")){ block = player.getTargetBlock((Set<Material>) null, 120); }else{ block = player.getTargetBlock(this.transparent, 120); } Location l = block.getLocation(); ItemStack stack2 = player.getItemInHand(); bloques = CLBManager.getManager().getConfig().getInt("Objects.DarkHole.number-of-blocks"); ticks = CLBManager.getManager().getConfig().getInt("Objects.DarkHole.time-between-one-block-and-the-next"); int amt = stack2.getAmount() - 1; if(amt == 0){ for(int i = 0; i <= 8; i++){ if(((player.getInventory().getItem(i) != null)) && (player.getInventory().getItem(i).getItemMeta().hasDisplayName())){ String item_name = player.getInventory().getItem(i).getItemMeta().getDisplayName(); //player.sendMessage("" + i); if((item_name.matches(darkName)) && (player.getInventory().getItem(i).getAmount() == 1)){ //player.sendMessage(item_name); player.getInventory().clear(i); i = 9; } } } }else{ stack2.setAmount(amt); } Timer c = new Timer(plugin, bloques, ticks, player, l); c.darkhole(); // for(int i = 0; i < player.getInventory().getSize(); i++){ // ItemStack itm = player.getInventory().getItem(i); // if((itm != null) && (itm.getItemMeta().getDisplayName().equals(lightName))){ //int amt = itm.getAmount() - 1; //itm.setAmount(amt); //player.getInventory().setItem(i, amt > 0 ? itm : null); //player.updateInventory(); } } } }
true
08496444c8c3b7546d197d1ed50ab3fa06526b90
Java
grainerm/fhj.swenga2018.project
/src/at/fh/swenga/controller/ActivityController.java
UTF-8
3,477
2.234375
2
[]
no_license
package at.fh.swenga.controller; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.annotation.Secured; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import at.fh.swenga.model.Activity; import at.fh.swenga.model.Drink; import at.fh.swenga.model.Food; import at.fh.swenga.model.GuestbookModel; import at.fh.swenga.model.Item; import at.fh.swenga.model.Sport; import at.fh.swenga.model.User; import at.fh.swenga.repositories.ActivityRepository; import at.fh.swenga.repositories.DrinkRepository; import at.fh.swenga.repositories.FoodRepository; import at.fh.swenga.repositories.ItemRepository; import at.fh.swenga.repositories.SportRepository; import at.fh.swenga.repositories.UserRepository; @Controller public class ActivityController { @Autowired private FoodRepository foodRepo; @Autowired private DrinkRepository drinkRepo; @Autowired private SportRepository sportRepo; @Autowired private ItemRepository itemRepo; @Autowired private UserRepository userRepo; @Autowired private ActivityRepository activityRepo; private Authentication authentication; private List<Activity> addedActivities= new ArrayList<Activity>(); @Secured({"ROLE_ADMIN", "ROLE_USER"}) @RequestMapping(value = "/activities", method = RequestMethod.GET) public String activities(Model model) { authentication = SecurityContextHolder.getContext().getAuthentication(); String nickname = authentication.getName(); List<Food> foods = foodRepo.findAll(); List<Drink> drinks = drinkRepo.findAll(); List<Sport> sports = sportRepo.findAll(); List<Activity> userActivities = new ArrayList<Activity>(); userActivities.addAll(activityRepo.findByUserName(nickname)); model.addAttribute("foods", foods); model.addAttribute("drinks", drinks); model.addAttribute("sports", sports); model.addAttribute("addedActivities", userActivities); return "activities"; } @Secured({"ROLE_ADMIN", "ROLE_USER"}) @RequestMapping(value = { "/add" }) public String find(Model model, @RequestParam(value="bezeichnung") String bezeichnung, @RequestParam(value="menge") int menge) { List<Food> foods = foodRepo.findAll(); List<Drink> drinks = drinkRepo.findAll(); List<Sport> sports = sportRepo.findAll(); authentication = SecurityContextHolder.getContext().getAuthentication(); String nickname = authentication.getName(); Item item = itemRepo.findByBezeichnung(bezeichnung).get(0); Activity activity = new Activity(new Date(), item, userRepo.findByName(nickname), menge); activity.setKalorienGesamt(menge * item.getKalorien()); activityRepo.save(activity); addedActivities.add(activity); model.addAttribute("foods", foods); model.addAttribute("drinks", drinks); model.addAttribute("sports", sports); model.addAttribute("sum", activity.getKalorienGesamt()); model.addAttribute("addedActivities", addedActivities); return activities(model); } }
true
4a59099a280c3fbbdee3d9dfb20a0fff6ede5f81
Java
visheshbanga/CRUD-Spring-Boot
/blogger/src/main/java/com/blogger/repo/RepoUser.java
UTF-8
629
2.203125
2
[]
no_license
package com.blogger.repo; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import com.blogger.entity.User; @Repository public interface RepoUser extends JpaRepository<User, Integer> { User findByUsername(String username); /** * Returns user containing given name * * @param username * @return {@link List} of {@link User} */ @Query("Select u from User u where u.username like %?1%") List<User> findByUsernameContaining(String username); User findById(Integer id); }
true
5b5256b6a8c3f0f541e4cc2a0976a5ce60007ba1
Java
PythonNovice5/catfish
/src/test/java/com/basware/bttf/pages/product_manager/buyer/agreements/AgentAgreementItemsPage.java
UTF-8
1,188
2.203125
2
[]
no_license
package com.basware.bttf.pages.product_manager.buyer.agreements; import com.basware.bttf.pages.product_manager.supplier.price_lists.PriceListDirectoryPage; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; public class AgentAgreementItemsPage extends PriceListDirectoryPage { @FindBy(linkText = "Create") public WebElement createButton; @FindBy(linkText = "Done") public WebElement doneButton; public AgentAgreementItemsPage() { PageFactory.initElements(driver,this); } @Override public String getExpectedUrl() { return getBaseUrl() + "/products/agreementItems/index"; } @Override public String getExpectedTitle() { return "Product Manager: Agreement Price List Items"; } public AgentAgreementCreateItemPage clickOnCreateButton() { waitUntillElementIsClickableAndClick(createButton); return new AgentAgreementCreateItemPage(); } public ManageAgreementPage clickOnDoneButton() { waitUntillElementIsClickableAndClick(doneButton); return new ManageAgreementPage(); } }
true
1eefd5302d5e73db8b4f8f94293bbc8dd327398f
Java
mustafacse/Geeksforgeeks
/src/org/mohsin/geek/Array/MiddlePointInSortedArray.java
UTF-8
616
3.53125
4
[]
no_license
package org.mohsin.geek.Array; import java.util.ArrayList; public class MiddlePointInSortedArray { public static int middlePoint(int arr[]){ int count = 0; ArrayList<Integer> res = new ArrayList<>(); for(int i = 0;i < arr.length;++i){ ++count; res.add(arr[i]); int j = i+1; while(j < arr.length && arr[i] == arr[j]) ++j; if(j == arr.length) break; i = j-1; } if(count%2 != 0) return res.get(res.size()/2); return -1; } public static void main(String[] args) { int arr[] = {1, 2, 3, 4, 4, 5, 6, 6, 6, 7}; System.out.println(middlePoint(arr)); } }
true
c61b4918fd821ea6fa5b2efaf8d479d89396db72
Java
lovo98/medicare
/src/main/java/com/Medicare/security/entity/pacientes.java
UTF-8
2,456
1.9375
2
[]
no_license
package com.Medicare.security.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class pacientes { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer idPaciente; @Column private String nombres; @Column private String apellidos; @Column private String edad; @Column private String dui; @Column private String telefono; @Column private String correo; @Column private String fechaNacimiento; @Column private String genero; @Column private String direccion; @Column private String encargado; @Column private String parentesco; @Column private String notas; public Integer getIdPaciente() { return idPaciente; } public void setIdPaciente(Integer idPaciente) { this.idPaciente = idPaciente; } public String getNombres() { return nombres; } public void setNombres(String nombres) { this.nombres = nombres; } public String getApellidos() { return apellidos; } public void setApellidos(String apellidos) { this.apellidos = apellidos; } public String getEdad() { return edad; } public void setEdad(String edad) { this.edad = edad; } public String getDui() { return dui; } public void setDui(String dui) { this.dui = dui; } public String getTelefono() { return telefono; } public void setTelefono(String telefono) { this.telefono = telefono; } public String getCorreo() { return correo; } public void setCorreo(String correo) { this.correo = correo; } public String getFechaNacimiento() { return fechaNacimiento; } public void setFechaNacimiento(String fechaNacimiento) { this.fechaNacimiento = fechaNacimiento; } public String getGenero() { return genero; } public void setGenero(String genero) { this.genero = genero; } public String getDireccion() { return direccion; } public void setDireccion(String direccion) { this.direccion = direccion; } public String getEncargado() { return encargado; } public void setEncargado(String encargado) { this.encargado = encargado; } public String getParentesco() { return parentesco; } public void setParentesco(String parentesco) { this.parentesco = parentesco; } public String getNotas() { return notas; } public void setNotas(String notas) { this.notas = notas; } }
true
4a9c5a64271d4a9ba93c49306bf877868f2f5a0d
Java
Dmitry1271/labsKremen
/Examples/Glava 2/VCz1/src/test/by/bsu/company/matrix/entity/MatrixTest.java
UTF-8
416
1.882813
2
[]
no_license
package test.by.bsu.company.matrix.entity; import by.bsu.company.matrix.entity.Matrix; import by.bsu.company.matrix.exception.MatrixException; import org.junit.Test; import static org.junit.Assert.*; /** * Created by HP on 17.01.2017. */ public class MatrixTest { @Test( expected = MatrixException.class ) public void createTest() throws MatrixException { Matrix m = new Matrix(2, -4); } }
true
21b0345a83d131f6feeb4383e706369794b07248
Java
jwalsh4867/jjw16-final-picassa-submission
/src/model/NegateExpression.java
UTF-8
1,009
3.15625
3
[]
no_license
package model; import java.util.List; import model.RGBColor; public class NegateExpression extends ParenExpression { protected NegateExpression(List<Expression> expressions) { super(expressions); } public static RGBColor negate (RGBColor var) { return new RGBColor(1 / var.getRed(), 1 / var.getGreen(), 1 / var.getBlue()); } @Override public RGBColor evaluate(double x, double y) { List<RGBColor> types = evaluateExpressions(x,y); return NegateExpression.negate(types.get(0)); } public static class Factory extends ParenExpression.Factory { @Override protected String command() { return "neg"; } @Override protected int operands() { return 1; } @Override protected ParenExpression makeExpression(List<Expression> Expressions) { return new NegateExpression(Expressions); } } }
true
b793c58ee33aa8f4622e834240d276b6a1410204
Java
ClaudiodeOliveira/TrabalhoEnade
/src/main/java/br/com/enade/model/Tbquestao.java
UTF-8
5,145
1.84375
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package br.com.enade.model; import java.io.Serializable; import java.util.Collection; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlTransient; /** * * @author claud */ @Entity @Table(name = "tbquestao") public class Tbquestao implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "idQuestao") private Long idQuestao; @Basic(optional = false) @Size(min = 1, max = 45) @Column(name = "descricaoQuestao") private String descricaoQuestao; @Size(max = 45) @Column(name = "alternativaA") private String alternativaA; @Size(max = 45) @Column(name = "alternativaB") private String alternativaB; @Size(max = 45) @Column(name = "alternativaC") private String alternativaC; @Size(max = 45) @Column(name = "alternativaD") private String alternativaD; @Size(max = 45) @Column(name = "alternativaE") private String alternativaE; @Column(name = "questaoCorreta") private Character questaoCorreta; @Basic(optional = false) @Column(name = "resposta") private String reposta; @Basic(optional = false) @Column(name = "estadoQuestao") private String estadoQuestao; @ManyToMany(mappedBy = "tbquestaoCollection", fetch = FetchType.LAZY) private Collection<Tbprova> tbprovaCollection; @JoinColumn(name = "tbTipoQuestao_idTipoQuestao", referencedColumnName = "idTipoQuestao") @ManyToOne(optional = false) private Tbtipoquestao tbTipoQuestaoidTipoQuestao; public Tbquestao() { } public Tbquestao(Long idQuestao) { this.idQuestao = idQuestao; } public Tbquestao(Long idQuestao, String descricaoQuestao, String estadoQuestao) { this.idQuestao = idQuestao; this.descricaoQuestao = descricaoQuestao; this.estadoQuestao = estadoQuestao; } public void gravarProva(Tbprova provaId) { tbprovaCollection.add(provaId); } public Long getIdQuestao() { return idQuestao; } public void setIdQuestao(Long idQuestao) { this.idQuestao = idQuestao; } public String getDescricaoQuestao() { return descricaoQuestao; } public void setDescricaoQuestao(String descricaoQuestao) { this.descricaoQuestao = descricaoQuestao; } public String getAlternativaA() { return alternativaA; } public void setAlternativaA(String alternativaA) { this.alternativaA = alternativaA; } public String getAlternativaB() { return alternativaB; } public void setAlternativaB(String alternativaB) { this.alternativaB = alternativaB; } public String getAlternativaC() { return alternativaC; } public void setAlternativaC(String alternativaC) { this.alternativaC = alternativaC; } public String getAlternativaD() { return alternativaD; } public void setAlternativaD(String alternativaD) { this.alternativaD = alternativaD; } public String getAlternativaE() { return alternativaE; } public void setAlternativaE(String alternativaE) { this.alternativaE = alternativaE; } public Character getQuestaoCorreta() { return questaoCorreta; } public void setQuestaoCorreta(Character questaoCorreta) { this.questaoCorreta = questaoCorreta; } public String getEstadoQuestao() { return estadoQuestao; } public void setEstadoQuestao(String estadoQuestao) { this.estadoQuestao = estadoQuestao; } @XmlTransient public Collection<Tbprova> getTbprovaCollection() { return tbprovaCollection; } public void setTbprovaCollection(Collection<Tbprova> tbprovaCollection) { this.tbprovaCollection = tbprovaCollection; } public Tbtipoquestao getTbTipoQuestaoidTipoQuestao() { return tbTipoQuestaoidTipoQuestao; } public void setTbTipoQuestaoidTipoQuestao(Tbtipoquestao tbTipoQuestaoidTipoQuestao) { this.tbTipoQuestaoidTipoQuestao = tbTipoQuestaoidTipoQuestao; } public String getReposta() { return reposta; } public void setReposta(String reposta) { this.reposta = reposta; } @Override public int hashCode() { int hash = 0; hash += (idQuestao != null ? idQuestao.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Tbquestao)) { return false; } Tbquestao other = (Tbquestao) object; if ((this.idQuestao == null && other.idQuestao != null) || (this.idQuestao != null && !this.idQuestao.equals(other.idQuestao))) { return false; } return true; } @Override public String toString() { return "br.com.enade.model.Tbquestao[ idQuestao=" + idQuestao + " ]"; } }
true
2809338a39af2f13e353db368ec4fab754e38fcd
Java
adityakumar001/DataStructures
/src/interfaces/Queue.java
UTF-8
132
2.84375
3
[]
no_license
package interfaces; public interface Queue<T> { void enqueue(T type); T dequeue(); int size(); T peekFront(); }
true
52e66bb8e3d520d24d7b66d12b62d76c1942bb58
Java
nathankim0/recordUpload
/app/src/main/java/com/example/simpleupload/Glob.java
UTF-8
254
1.945313
2
[]
no_license
package com.example.simpleupload; public class Glob { public String getmFilePath() { return mFilePath; } public void setmFilePath(String mFilePath) { this.mFilePath = mFilePath; } public String mFilePath = null; }
true
a96dec9e90b09eb7096cec56b2dfd02472c045e6
Java
HasanCanKose/strategy-pattern-project
/src/main/java/strategy/pattern/example/strategy/CourseStrategy.java
UTF-8
1,076
2.875
3
[ "MIT" ]
permissive
package strategy.pattern.example.strategy; import org.springframework.stereotype.Component; import strategy.pattern.example.models.Course; import strategy.pattern.example.repositories.CourseRepository; import java.util.List; @Component public class CourseStrategy implements CrudStrategy<Course> { private final CourseRepository courseRepository; public CourseStrategy(CourseRepository courseRepository){ this.courseRepository = courseRepository; } @Override public List<Course> getAll() { return courseRepository.findAll(); } @Override public Course getOne(String name) { List<Course> courses = getAll(); return courses.stream().filter(course -> course.getName().equals(name)).findFirst().get(); } @Override public void add(Course course) { courseRepository.save(course); } @Override public void update(Course course, int id) { courseRepository.save(course); } @Override public void delete(int id) { courseRepository.deleteById(id); } }
true
3eaed9f8aa94d24f09b9e317b9bbcd31279d6fcf
Java
zhang-yan-talendbj/deppDemo
/com.caribe.stone.core/src/test/java/com/caribe/stone/utils/DateUtilsTest.java
UTF-8
44,036
2.734375
3
[]
no_license
package com.caribe.stone.utils; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import junit.framework.TestCase; import junit.textui.TestRunner; /** * @author srini * * Created: 2/07/2004 * */ public class DateUtilsTest extends TestCase { public DateUtilsTest(String testName) { super(testName); } public static void main(String[] args) { // TestRunner.run(DateUtilsTest.class); TestRunner.run(new DateUtilsTest("testMonthsBetween28Feb2000And1Oct2000")); } public void testDaysBetweenTwoSameDays() { Date from = new Date(); assertEquals(0, DateUtils.calculateDaysBetween(from, new Date())); } public void testDaysBetweenDaysWithDifferentTimestamps() throws Exception { Date from = new Date(); Thread.sleep(500); assertEquals(0, DateUtils.calculateDaysBetween(from, new Date())); } public void testDaysBetweenDaysWithOneDayDifference() throws Exception { Date from = DateUtils.createStartOfDay(1900, 1, 1); Date to = DateUtils.createStartOfDay(1900, 1, 2); assertEquals(1, DateUtils.calculateDaysBetween(from, to)); } public void testDaysBetweenDaysWithTwoDaysDifference() throws Exception { Date from = DateUtils.createStartOfDay(1900, 1, 1); Date to = DateUtils.createStartOfDay(1900, 1, 3); assertEquals(2, DateUtils.calculateDaysBetween(from, to)); } public void testDaysBetweenDaysWithOneMonthDifference() throws Exception { Date from = DateUtils.createStartOfDay(1900, 1, 1); Date to = DateUtils.createStartOfDay(1900, 2, 1); assertEquals(31, DateUtils.calculateDaysBetween(from, to)); } public void test28DaysInNonLeapFeburary() throws Exception { Date from = DateUtils.createStartOfDay(1901, 2, 1); Date to = DateUtils.createStartOfDay(1901, 3, 1); assertEquals(28, DateUtils.calculateDaysBetween(from, to)); } public void test29DaysInLeapFeburary() throws Exception { Date from = DateUtils.createStartOfDay(2004, 2, 1); Date to = DateUtils.createStartOfDay(2004, 3, 1); assertEquals(29, DateUtils.calculateDaysBetween(from, to)); } private void testBetween(Date yesterday, Date today, Date tomorrow) { assertTrue("test dates invalid", yesterday.before(today)); assertTrue("test dates invalid", today.before(tomorrow)); // test between assertTrue("left < target < right", DateUtils.between(today, yesterday, tomorrow)); assertTrue("left = target = right", DateUtils.between(today, today, today)); assertTrue("left = target < right", DateUtils.between(today, today, tomorrow)); assertTrue("left < target = right", DateUtils.between(today, yesterday, today)); assertTrue("left < target, right = null", DateUtils.between(today, yesterday, null)); assertTrue("left = null, target < right", DateUtils.between(today, null, tomorrow)); assertTrue("left = null, right = null, target != null", DateUtils.between(today, null, null)); // test not between assertTrue("left < right < target", !DateUtils.between(tomorrow, yesterday, today)); assertTrue("target < left < right", !DateUtils.between(yesterday, today, tomorrow)); assertTrue("left, right < target", !DateUtils.between(today, yesterday, yesterday)); assertTrue("left, right > target", !DateUtils.between(today, tomorrow, tomorrow)); assertTrue("left = null, right > target", !DateUtils.between(tomorrow, null, today)); assertTrue("target < left, right = null", !DateUtils.between(yesterday, today, null)); } public void testBetween() { Calendar calendar = Calendar.getInstance(); Date today = new Date(); calendar.add(Calendar.DAY_OF_YEAR, -1); Date yesterday = calendar.getTime(); calendar.add(Calendar.DAY_OF_YEAR, 2); Date tomorrow = calendar.getTime(); this.testBetween(yesterday, today, tomorrow); // make sure we don't actually need different days Date now = new Date(); Date justBefore = new Date(now.getTime() - 1); Date justAfter = new Date(now.getTime() + 1); this.testBetween(justBefore, now, justAfter); } /** * Test addRawOffsetToDate. Ignore issues dealing with maintaining month end * etc. */ public void testAddRawOffsetToDate() throws Exception { int month = Calendar.MONTH; Date tempDate; // basic stuff tempDate = DateUtils.addRawOffsetToDate(mar2801, month, 1); assertEquals("mar2801 + 1 month", april2801, tempDate); tempDate = DateUtils.addRawOffsetToDate(jan2801, month, 2); assertEquals("jan2801 + 2 month", mar2801, tempDate); tempDate = DateUtils.addRawOffsetToDate(jan3101, month, 12); assertEquals("jan3101 + 12 month", jan3102, tempDate); tempDate = DateUtils.addRawOffsetToDate(jan3101, month, 3); assertEquals("jan3101 + 3 month", april3001, tempDate); tempDate = DateUtils.addRawOffsetToDate(jan3101, month, 4); assertEquals("jan3101 + 4 month", may3101, tempDate); tempDate = DateUtils.addRawOffsetToDate(mar3101, month, 2); assertEquals("mar3101 + 2 month", may3101, tempDate); tempDate = DateUtils.addRawOffsetToDate(jan3101, month, 2); assertEquals("jan3101 + 2 month", mar3101, tempDate); tempDate = DateUtils.addRawOffsetToDate(mar3101, month, -2); assertEquals("mar3101 - 2 month", jan3101, tempDate); tempDate = DateUtils.createStartOfDay(2001, 1, 32); assertEquals("jan3201 -> feb0101", feb0101, tempDate); // test adding from jan to feb tempDate = DateUtils.addRawOffsetToDate(jan2801, month, 1); assertEquals("Jan2801 + 1 month", feb2801, tempDate); tempDate = DateUtils.addRawOffsetToDate(jan2901, month, 1); assertEquals("Jan2901 + 1 month", feb2801, tempDate); tempDate = DateUtils.addRawOffsetToDate(jan3001, month, 1); assertEquals("Jan3001 + 1 month", feb2801, tempDate); tempDate = DateUtils.addRawOffsetToDate(jan3101, month, 1); assertEquals("Jan3101 + 1 month", feb2801, tempDate); // test going from march back to feb tempDate = DateUtils.addRawOffsetToDate(mar2801, month, -1); assertEquals("mar2801 - 1 month", feb2801, tempDate); tempDate = DateUtils.addRawOffsetToDate(mar2901, month, -1); assertEquals("mar2901 - 1 month", feb2801, tempDate); tempDate = DateUtils.addRawOffsetToDate(mar3001, month, -1); assertEquals("mar3001 - 1 month", feb2801, tempDate); tempDate = DateUtils.addRawOffsetToDate(mar3101, month, -1); assertEquals("mar3101 - 1 month", feb2801, tempDate); // test going from feb to mar/jan // end of month adjustments NOT done automatically - expected. tempDate = DateUtils.addRawOffsetToDate(feb2801, month, 1); assertEquals("feb2801 + 1 month", mar2801, tempDate); tempDate = DateUtils.addRawOffsetToDate(feb2801, month, -1); assertEquals("feb2801 - 1 month", jan2801, tempDate); // some basic leap year "month" stuff tempDate = DateUtils.addRawOffsetToDate(feb2904, month, 1); assertEquals("feb2904 + 1 month", mar2904, tempDate); tempDate = DateUtils.addRawOffsetToDate(feb2904, month, -1); assertEquals("feb2904 - 1 month", jan2904, tempDate); tempDate = DateUtils.addRawOffsetToDate(jan2804, month, 1); assertEquals("Jan2804 + 1 month", feb2804, tempDate); tempDate = DateUtils.addRawOffsetToDate(jan2904, month, 1); assertEquals("Jan2904 + 1 month", feb2904, tempDate); tempDate = DateUtils.addRawOffsetToDate(jan3004, month, 1); assertEquals("Jan3004 + 1 month", feb2904, tempDate); tempDate = DateUtils.addRawOffsetToDate(jan3104, month, 1); assertEquals("Jan3104 + 1 month", feb2904, tempDate); tempDate = DateUtils.addRawOffsetToDate(mar2804, month, -1); assertEquals("mar2804 - 1 month", feb2804, tempDate); tempDate = DateUtils.addRawOffsetToDate(mar2904, month, -1); assertEquals("mar2904 - 1 month", feb2904, tempDate); tempDate = DateUtils.addRawOffsetToDate(mar3004, month, -1); assertEquals("mar3004 - 1 month", feb2904, tempDate); tempDate = DateUtils.addRawOffsetToDate(mar3104, month, -1); assertEquals("mar3104 - 1 month", feb2904, tempDate); // leap year "year" stuff tempDate = DateUtils.addRawOffsetToDate(feb2904, Calendar.YEAR, 3); assertEquals("feb2904 + 3 year", feb2807, tempDate); tempDate = DateUtils.addRawOffsetToDate(feb2904, Calendar.YEAR, 4); assertEquals("feb2904 + 4 year", feb2908, tempDate); tempDate = DateUtils.addRawOffsetToDate(feb2908, Calendar.YEAR, -1); assertEquals("feb2908 - 1 year", feb2807, tempDate); } /** * Method testSimpleDateParsing. * * @throws Exception */ private Date feb2801, mar2801, mar2901, mar3001, mar3101, jan2801, jan2901, jan3001, jan3101; private Date april2801, april3001, may3101; private Date feb2804, feb2904, mar2804, mar2904, mar3004, mar3104, jan2804, jan2904, jan3004, jan3104; private Date feb2807, feb2908, feb0101; private Date jan3102; @Override protected void setUp() throws Exception { super.setUp(); feb0101 = DateUtils.createStartOfDay(2001, 2, 1); feb2801 = DateUtils.createStartOfDay(2001, 2, 28); mar2801 = DateUtils.createStartOfDay(2001, 3, 28); mar2901 = DateUtils.createStartOfDay(2001, 3, 29); mar3001 = DateUtils.createStartOfDay(2001, 3, 30); mar3101 = DateUtils.createStartOfDay(2001, 3, 31); jan2801 = DateUtils.createStartOfDay(2001, 1, 28); jan2901 = DateUtils.createStartOfDay(2001, 1, 29); jan3001 = DateUtils.createStartOfDay(2001, 1, 30); jan3101 = DateUtils.createStartOfDay(2001, 1, 31); april2801 = DateUtils.createStartOfDay(2001, 4, 28); april3001 = DateUtils.createStartOfDay(2001, 4, 30); may3101 = DateUtils.createStartOfDay(2001, 5, 31); feb2804 = DateUtils.createStartOfDay(2004, 2, 28); feb2904 = DateUtils.createStartOfDay(2004, 2, 29); mar2804 = DateUtils.createStartOfDay(2004, 3, 28); mar2904 = DateUtils.createStartOfDay(2004, 3, 29); mar3004 = DateUtils.createStartOfDay(2004, 3, 30); mar3104 = DateUtils.createStartOfDay(2004, 3, 31); jan2804 = DateUtils.createStartOfDay(2004, 1, 28); jan2904 = DateUtils.createStartOfDay(2004, 1, 29); jan3004 = DateUtils.createStartOfDay(2004, 1, 30); jan3104 = DateUtils.createStartOfDay(2004, 1, 31); feb2807 = DateUtils.createStartOfDay(2007, 2, 28); feb2908 = DateUtils.createStartOfDay(2008, 2, 29); jan3102 = DateUtils.createStartOfDay(2002, 1, 31); } @Override protected void tearDown() throws Exception { super.tearDown(); } public void testDatesBetween22ndOct2004And11May1998() { Date firstDate = DateUtils.createStartOfDay(2004, 10, 22); Date secondDate = DateUtils.createStartOfDay(1998, 5, 11); // 234 + 365 + 366 + 365 + 365 + 365 + 295 = 2356 assertEquals(2356, DateUtils.calculateDaysBetween(secondDate, firstDate)); } public void testDatesBetweenTwoSameDates() { Date firstDate = DateUtils.createStartOfDay(2004, 10, 22); Date secondDate = (Date) firstDate.clone(); assertEquals(0, DateUtils.calculateDaysBetween(secondDate, firstDate)); } public void testMonthsBetweenSameDays() { Date date1 = DateUtils.createStartOfDay(2000, 1, 1); long[] monthsBetweenDays = DateUtils.monthsBetween(date1, date1); assertEquals(2, monthsBetweenDays.length); assertEquals(0, monthsBetweenDays[0]); assertEquals(0, monthsBetweenDays[1]); } public void testMonthsBetweenOneExactMonth() { Date date1 = DateUtils.createStartOfDay(2000, 1, 1); Date date2 = DateUtils.createStartOfDay(2000, 2, 1); long[] monthsBetweenDays = DateUtils.monthsBetween(date1, date2); assertEquals(2, monthsBetweenDays.length); assertEquals(1, monthsBetweenDays[0]); assertEquals(0, monthsBetweenDays[1]); } public void testMonthsBetweenOneMonthAndOneDay() { Date date1 = DateUtils.createStartOfDay(2000, 1, 1); Date date2 = DateUtils.createStartOfDay(2000, 2, 2); long[] monthsBetweenDays = DateUtils.monthsBetween(date1, date2); assertEquals(2, monthsBetweenDays.length); assertEquals(1, monthsBetweenDays[0]); assertEquals(1, monthsBetweenDays[1]); } public void testMonthsBetweenOneMonthAnd29DaysInLeapYear() { Date date1 = DateUtils.createStartOfDay(2000, 1, 1); Date date2 = DateUtils.addRawOffsetToDate(DateUtils.addRawOffsetToDate(date1, Calendar.MONTH, 1), Calendar.DATE, 29); long[] monthsBetweenDays = DateUtils.monthsBetween(date1, date2); assertEquals(2, monthsBetweenDays.length); assertEquals(2, monthsBetweenDays[0]); assertEquals(0, monthsBetweenDays[1]); } public void testMonthsBetweenOneMonthAnd29DaysInNonLeapYear() { Date date1 = DateUtils.createStartOfDay(2001, 1, 1); Date date2 = DateUtils.addRawOffsetToDate(DateUtils.addRawOffsetToDate(date1, Calendar.MONTH, 1), Calendar.DATE, 29); long[] monthsBetweenDays = DateUtils.monthsBetween(date1, date2); assertEquals(2, monthsBetweenDays.length); assertEquals(2, monthsBetweenDays[0]); assertEquals(1, monthsBetweenDays[1]); } public void testMonthsBetweenDaysLessThanOneMonthApart() { Date date1 = DateUtils.createStartOfDay(2001, 3, 5); Date date2 = DateUtils.createStartOfDay(2001, 4, 4); long[] monthsBetweenDays = DateUtils.monthsBetween(date1, date2); assertEquals(2, monthsBetweenDays.length); assertEquals(0, monthsBetweenDays[0]); assertEquals(30, monthsBetweenDays[1]); } // public void testMonthsBetweenConsecutiveDays() { // Date date1 = DateUtils.createStartOfDay(); // Date date2 = DateUtils.createStartOfNextDay(); // long[] monthsBetweenDays = DateUtils.monthsBetween(date1, date2); // assertEquals(2, monthsBetweenDays.length); // assertEquals(0, monthsBetweenDays[0]); // assertEquals(1, monthsBetweenDays[1]); // } // // public void testMonthsBetweenConsecutiveDaysInterchanged() { // Date date1 = DateUtils.createStartOfDay(); // Date date2 = DateUtils.createStartOfNextDay(); // long[] monthsBetweenDays = DateUtils.monthsBetween(date1, date2); // assertEquals(2, monthsBetweenDays.length); // assertEquals(0, monthsBetweenDays[0]); // assertEquals(1, monthsBetweenDays[1]); // } public void testMonthsBetweenConsecutiveDaysOnMonthBorder() { Date date1 = DateUtils.createStartOfDay(2001, 1, 31); Date date2 = DateUtils.createStartOfNextDay(date1); long[] monthsBetweenDays = DateUtils.monthsBetween(date1, date2); assertEquals(2, monthsBetweenDays.length); assertEquals(0, monthsBetweenDays[0]); assertEquals(1, monthsBetweenDays[1]); } public void testMonthsBetweenConsecutiveMonthsInLeapYearInterchanged() { Date date1 = DateUtils.createStartOfDay(2000, 2, 25); Date date2 = DateUtils.createStartOfDay(2000, 3, 25); try { DateUtils.monthsBetween(date2, date1); fail("IllegalArgumentException expected"); } catch (IllegalArgumentException e) { } } public void testMonthsBetween23102004And24112004() { Date date1 = DateUtils.createStartOfDay(2004, 10, 23); Date date2 = DateUtils.createStartOfDay(2004, 11, 24); long[] monthsBetweenDays = DateUtils.monthsBetween(date1, date2); assertEquals(2, monthsBetweenDays.length); assertEquals(1, monthsBetweenDays[0]); assertEquals(1, monthsBetweenDays[1]); } public void testMonthsBetween23102004And24122005() { Date date1 = DateUtils.createStartOfDay(2004, 10, 23); Date date2 = DateUtils.createStartOfDay(2005, 12, 24); long[] monthsBetweenDays = DateUtils.monthsBetween(date1, date2); assertEquals(2, monthsBetweenDays.length); assertEquals(14, monthsBetweenDays[0]); assertEquals(1, monthsBetweenDays[1]); } public void testMonthsBetweenDaysOnYearBorder() { Date date1 = DateUtils.createStartOfDay(2004, 11, 30); Date date2 = DateUtils.createStartOfDay(2005, 1, 1); long[] monthsBetweenDays = DateUtils.monthsBetween(date1, date2); assertEquals(2, monthsBetweenDays.length); assertEquals(1, monthsBetweenDays[0]); assertEquals(2, monthsBetweenDays[1]); } public void testMonthsBetweenDaysOnYearBorder2() { Date date1 = DateUtils.createStartOfDay(2004, 12, 30); Date date2 = DateUtils.createStartOfDay(2005, 1, 1); long[] monthsBetweenDays = DateUtils.monthsBetween(date1, date2); assertEquals(2, monthsBetweenDays.length); assertEquals(0, monthsBetweenDays[0]); assertEquals(2, monthsBetweenDays[1]); } public void testMonthsBetween1Feb2004And29Feb2004() { Date date1 = DateUtils.createStartOfDay(2004, 2, 1); Date date2 = DateUtils.createStartOfDay(2004, 2, 29); long[] monthsBetweenDays = DateUtils.monthsBetween(date1, date2); assertEquals(2, monthsBetweenDays.length); assertEquals(0, monthsBetweenDays[0]); assertEquals(28, monthsBetweenDays[1]); } public void testMonthsBetween1Feb2004And30Feb2004() { Date date1 = DateUtils.createStartOfDay(2004, 2, 1); Date date2 = DateUtils.createStartOfDay(2004, 2, 30); long[] monthsBetweenDays = DateUtils.monthsBetween(date1, date2); assertEquals(2, monthsBetweenDays.length); assertEquals(1, monthsBetweenDays[0]); assertEquals(0, monthsBetweenDays[1]); } public void testMonthsBetween1Feb2004And1Mar2004() { Date date1 = DateUtils.createStartOfDay(2004, 2, 1); Date date2 = DateUtils.createStartOfDay(2004, 3, 1); long[] monthsBetweenDays = DateUtils.monthsBetween(date1, date2); assertEquals(2, monthsBetweenDays.length); assertEquals(1, monthsBetweenDays[0]); assertEquals(0, monthsBetweenDays[1]); } public void testMonthsBetween1Mar2004And31Mar2004() { Date date1 = DateUtils.createStartOfDay(2004, 3, 1); Date date2 = DateUtils.createStartOfDay(2004, 3, 31); long[] monthsBetweenDays = DateUtils.monthsBetween(date1, date2); assertEquals(2, monthsBetweenDays.length); assertEquals(0, monthsBetweenDays[0]); assertEquals(30, monthsBetweenDays[1]); } public void testMonthsBetween1Mar2004And1Apr2004() { Date date1 = DateUtils.createStartOfDay(2004, 3, 1); Date date2 = DateUtils.createStartOfDay(2004, 4, 1); long[] monthsBetweenDays = DateUtils.monthsBetween(date1, date2); assertEquals(2, monthsBetweenDays.length); assertEquals(1, monthsBetweenDays[0]); assertEquals(0, monthsBetweenDays[1]); } public void testMonthsBetween1Feb2004And2Mar2004() { Date date1 = DateUtils.createStartOfDay(2004, 2, 1); Date date2 = DateUtils.createStartOfDay(2004, 3, 2); long[] monthsBetweenDays = DateUtils.monthsBetween(date1, date2); assertEquals(2, monthsBetweenDays.length); assertEquals(1, monthsBetweenDays[0]); assertEquals(1, monthsBetweenDays[1]); } public void testMonthsBetween1Feb2004And3Mar2004() { Date date1 = DateUtils.createStartOfDay(2004, 2, 1); Date date2 = DateUtils.createStartOfDay(2004, 3, 3); long[] monthsBetweenDays = DateUtils.monthsBetween(date1, date2); assertEquals(2, monthsBetweenDays.length); assertEquals(1, monthsBetweenDays[0]); assertEquals(2, monthsBetweenDays[1]); } /* public void testMonthsBetweenTodayAndMonthAndOneDayFromToday() { Date date1 = DateUtils.createStartOfDay(); Date date2 = DateUtils.createStartOfNextDay(DateUtils.addRawOffsetToDate(date1, Calendar.MONTH, 1)); long[] monthsBetweenDays = DateUtils.monthsBetween(date1, date2); assertEquals(2, monthsBetweenDays.length); assertEquals(1, monthsBetweenDays[0]); assertEquals(1, monthsBetweenDays[1]); } public void testMonthsBetweenSept5AndOctober6MonthAndOneDay() { Date date1 = DateUtils.createStartOfDay(2011, 9, 2); Date date2 = DateUtils.createStartOfDay(2011, 10, 6); long[] monthsBetweenDays = DateUtils.monthsBetween(date1, date2); assertEquals(2, monthsBetweenDays.length); assertEquals(1, monthsBetweenDays[0]); assertEquals(1, monthsBetweenDays[1]); } */ public void testMonthsBetween11Jun2004And11Dec2004() { Date date1 = DateUtils.createStartOfDay(2004, 6, 11); Date date2 = DateUtils.createStartOfDay(2004, 12, 11); long[] monthsBetweenDays = DateUtils.monthsBetween(date1, date2); assertEquals(2, monthsBetweenDays.length); assertEquals(6, monthsBetweenDays[0]); assertEquals(0, monthsBetweenDays[1]); } public void testMonthsBetween11Jun2004And11Jan2005() { Date date1 = DateUtils.createStartOfDay(2004, 6, 11); Date date2 = DateUtils.createStartOfDay(2005, 1, 11); long[] monthsBetweenDays = DateUtils.monthsBetween(date1, date2); assertEquals(2, monthsBetweenDays.length); assertEquals(7, monthsBetweenDays[0]); assertEquals(0, monthsBetweenDays[1]); } public void testMonthsBetween07Oct2004And06Jan2005() { Date date1 = DateUtils.createStartOfDay(2004, 10, 07); Date date2 = DateUtils.createStartOfDay(2005, 1, 07); long[] monthsBetweenDays = DateUtils.monthsBetween(date1, date2); assertEquals(2, monthsBetweenDays.length); assertEquals(3, monthsBetweenDays[0]); assertEquals(0, monthsBetweenDays[1]); } public void testMonthsBetween29Feb2004And01Mar2004() { Date date1 = DateUtils.createStartOfDay(2004, 2, 29); Date date2 = DateUtils.createStartOfDay(2004, 3, 1); long[] monthsBetweenDays = DateUtils.monthsBetween(date1, date2); assertEquals(2, monthsBetweenDays.length); assertEquals(0, monthsBetweenDays[0]); assertEquals(1, monthsBetweenDays[1]); } public void testMonthsBetween29Feb2004And29Mar2004() { Date date1 = DateUtils.createStartOfDay(2004, 2, 29); Date date2 = DateUtils.createStartOfDay(2004, 3, 29); long[] monthsBetweenDays = DateUtils.monthsBetween(date1, date2); assertEquals(2, monthsBetweenDays.length); assertEquals(1, monthsBetweenDays[0]); assertEquals(0, monthsBetweenDays[1]); } public void testMonthsBetween29Feb2004And01Mar2005() { Date date1 = DateUtils.createStartOfDay(2004, 2, 29); Date date2 = DateUtils.createStartOfDay(2005, 3, 1); long[] monthsBetweenDays = DateUtils.monthsBetween(date1, date2); assertEquals(2, monthsBetweenDays.length); assertEquals(12, monthsBetweenDays[0]); assertEquals(1, monthsBetweenDays[1]); } public void testMonthsBetween28Feb2004And29Mar2004() { Date date1 = DateUtils.createStartOfDay(2004, 2, 28); Date date2 = DateUtils.createStartOfDay(2004, 3, 29); long[] monthsBetweenDays = DateUtils.monthsBetween(date1, date2); assertEquals(2, monthsBetweenDays.length); assertEquals(1, monthsBetweenDays[0]); assertEquals(1, monthsBetweenDays[1]); } public void testMonthsBetween1Feb2004And1Feb2005() { Date date1 = DateUtils.createStartOfDay(2004, 2, 1); Date date2 = DateUtils.createStartOfDay(2005, 2, 1); long[] monthsBetweenDays = DateUtils.monthsBetween(date1, date2); assertEquals(2, monthsBetweenDays.length); assertEquals(12, monthsBetweenDays[0]); assertEquals(0, monthsBetweenDays[1]); } public void testMonthsBetween1Jan2004And1Feb2004() { Date date1 = DateUtils.createStartOfDay(2004, 1, 1); Date date2 = DateUtils.createStartOfDay(2004, 2, 1); long[] monthsBetweenDays = DateUtils.monthsBetween(date1, date2); assertEquals(2, monthsBetweenDays.length); assertEquals(1, monthsBetweenDays[0]); assertEquals(0, monthsBetweenDays[1]); } public void testMonthsBetween1Jan2004And1Feb2005() { Date date1 = DateUtils.createStartOfDay(2004, 1, 1); Date date2 = DateUtils.createStartOfDay(2005, 2, 1); long[] monthsBetweenDays = DateUtils.monthsBetween(date1, date2); assertEquals(2, monthsBetweenDays.length); assertEquals(13, monthsBetweenDays[0]); assertEquals(0, monthsBetweenDays[1]); } public void testMonthsBetween1Jan2000And1Mar2005() { Date date1 = DateUtils.createStartOfDay(2000, 1, 1); Date date2 = DateUtils.createStartOfDay(2005, 3, 1); long[] monthsBetweenDays = DateUtils.monthsBetween(date1, date2); assertEquals(2, monthsBetweenDays.length); assertEquals(62, monthsBetweenDays[0]); assertEquals(0, monthsBetweenDays[1]); } public void testMonthsBetween1Feb2000And28Feb2000() { Date date1 = DateUtils.createStartOfDay(2000, 2, 1); Date date2 = DateUtils.createStartOfDay(2000, 2, 29); long[] monthsBetweenDays = DateUtils.monthsBetween(date1, date2); assertEquals(2, monthsBetweenDays.length); assertEquals(0, monthsBetweenDays[0]); assertEquals(28, monthsBetweenDays[1]); } public void testMonthsBetween1Feb2000And29Feb2000() { Date date1 = DateUtils.createStartOfDay(2000, 2, 1); Date date2 = DateUtils.createStartOfDay(2000, 3, 1); long[] monthsBetweenDays = DateUtils.monthsBetween(date1, date2); assertEquals(2, monthsBetweenDays.length); assertEquals(1, monthsBetweenDays[0]); assertEquals(0, monthsBetweenDays[1]); } public void testMonthsBetween10Sep1979And1Dec2004() { Date date1 = DateUtils.createStartOfDay(1979, 9, 10); Date date2 = DateUtils.createStartOfDay(2004, 12, 1); long[] monthsBetweenDays = DateUtils.monthsBetween(date1, date2); assertEquals(2, monthsBetweenDays.length); assertEquals(302, monthsBetweenDays[0]); assertEquals(21, monthsBetweenDays[1]); } public void testMonthsBetween1Jan2008And29Feb2008() { Date date1 = DateUtils.createStartOfDay(2008, 1, 1); Date date2 = DateUtils.createStartOfDay(2008, 2, 29); long[] monthsBetweenDays = DateUtils.monthsBetween(date1, date2); assertEquals(2, monthsBetweenDays.length); assertEquals(1, monthsBetweenDays[0]); assertEquals(28, monthsBetweenDays[1]); } public void testMonthsBetween1Jan2008And1Mar2008() { Date date1 = DateUtils.createStartOfDay(2008, 1, 1); Date date2 = DateUtils.createStartOfDay(2008, 3, 1); long[] monthsBetweenDays = DateUtils.monthsBetween(date1, date2); assertEquals(2, monthsBetweenDays.length); assertEquals(2, monthsBetweenDays[0]); assertEquals(0, monthsBetweenDays[1]); } public void testMonthsBetween1Feb2100And28Feb2100() { Date date1 = DateUtils.createStartOfDay(2100, 2, 1); Date date2 = DateUtils.createStartOfDay(2100, 2, 28); long[] monthsBetweenDays = DateUtils.monthsBetween(date1, date2); assertEquals(2, monthsBetweenDays.length); assertEquals(0, monthsBetweenDays[0]); assertEquals(27, monthsBetweenDays[1]); } public void testMonthsBetween28Feb2000And1Oct2000() { Date date1 = DateUtils.createStartOfDay(2000, 2, 28); Date date2 = DateUtils.createStartOfDay(2000, 10, 1); long[] monthsBetweenDays = DateUtils.monthsBetween(date1, date2); assertEquals(2, monthsBetweenDays.length); assertEquals(7, monthsBetweenDays[0]); assertEquals(3, monthsBetweenDays[1]); } public void testMonthsBetween25Mar2000And1Oct2000() { Date date1 = DateUtils.createStartOfDay(2000, 3, 25); Date date2 = DateUtils.createStartOfDay(2000, 10, 1); long[] monthsBetweenDays = DateUtils.monthsBetween(date1, date2); assertEquals(2, monthsBetweenDays.length); assertEquals(6, monthsBetweenDays[0]); assertEquals(6, monthsBetweenDays[1]); } public void testMonthsBetweenFebAndMarSameYearDay1MoreThanD2() { Date date1 = DateUtils.createStartOfDay(2000, 2, 29); Date date2 = DateUtils.createStartOfDay(2000, 3, 1); long[] monthsBetweenDays = DateUtils.monthsBetween(date1, date2); assertEquals(2, monthsBetweenDays.length); assertEquals(0, monthsBetweenDays[0]); assertEquals(1, monthsBetweenDays[1]); } public void testMonthsBetweenFebAndMarSameYearDay1LessThanD2() { Date date1 = DateUtils.createStartOfDay(2000, 2, 1); Date date2 = DateUtils.createStartOfDay(2000, 3, 25); long[] monthsBetweenDays = DateUtils.monthsBetween(date1, date2); assertEquals(2, monthsBetweenDays.length); assertEquals(1, monthsBetweenDays[0]); assertEquals(24, monthsBetweenDays[1]); } public void testMonthsBetweenFebAndMarSameYearDay1LessThanD2Interchanged() { Date date1 = DateUtils.createStartOfDay(2000, 2, 1); Date date2 = DateUtils.createStartOfDay(2000, 3, 25); try { DateUtils.monthsBetween(date2, date1); fail("IllegalArgumentException expected"); } catch (IllegalArgumentException e) { } } public void testMonthsBetweenConsecutiveMonthsInLeapYear() { Date date1 = DateUtils.createStartOfDay(2000, 2, 25); Date date2 = DateUtils.createStartOfDay(2000, 3, 25); long[] monthsBetweenDays = DateUtils.monthsBetween(date1, date2); assertEquals(2, monthsBetweenDays.length); assertEquals(1, monthsBetweenDays[0]); assertEquals(0, monthsBetweenDays[1]); } public void testWorkDays() throws Exception { // less than a week assertWorkDays(0, "24/03/2005", "24/03/2005"); assertWorkDays(1, "24/03/2005", "25/03/2005"); assertWorkDays(1, "25/03/2005", "24/03/2005"); assertWorkDays(4, "21/03/2005", "25/03/2005"); assertWorkDays(1, "25/03/2005", "28/03/2005"); // more than a week assertWorkDays(20, "1/03/2005", "29/03/2005"); assertWorkDays(19, "1/03/2005", "28/03/2005"); assertWorkDays(18, "1/03/2005", "25/03/2005"); assertWorkDays(5, "1/03/2005", "8/03/2005"); assertWorkDays(4, "1/03/2005", "7/03/2005"); // days on weekends assertWorkDays(3, "1/03/2005", "4/03/2005"); assertWorkDays(3, "1/03/2005", "6/03/2005"); assertWorkDays(3, "1/03/2005", "5/03/2005"); assertWorkDays(7, "4/03/2005", "15/03/2005"); assertWorkDays(6, "5/03/2005", "15/03/2005"); assertWorkDays(6, "6/03/2005", "15/03/2005"); assertWorkDays(6, "7/03/2005", "15/03/2005"); assertWorkDays(0, "31/12/2004", "1/1/2005"); assertWorkDays(260, "31/12/2004", "30/12/2005"); // Times within a day assertWorkDaysTime(0, "24/03/2005 02:30", "24/03/2005 21:30"); assertWorkDaysTime(0, "24/03/2005 00:00", "24/03/2005 23:59"); assertWorkDaysTime(1, "24/03/2005 23:59", "25/03/2005 00:00"); assertWorkDaysTime(1, "24/03/2005 02:30", "25/03/2005 21:30"); } public void assertWorkDays(int days, String from, String to) throws Exception { DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); assertEquals(days, DateUtils.calculateWorkingDaysBetween(df.parse(from), df.parse(to))); } public void assertWorkDaysTime(int days, String from, String to) throws Exception { DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm"); assertEquals(days, DateUtils.calculateWorkingDaysBetween(df.parse(from), df.parse(to))); } public void assertDatesEqual(String expected, String got) throws Exception { DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss:SSS"); assertEquals(df.parse(expected), df.parse(got)); } public void assertEndOfDayIs(String day, String endOfDay) throws Exception { DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss.SSS"); assertEquals(df.parse(endOfDay), DateUtils.endOfDay(df.parse(day))); } public void assertEndOfDayWithPivotHourIs(long pivotHour, String day, String endOfDay) throws Exception { DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss.SSS"); assertEquals(df.parse(endOfDay), DateUtils.getEndOfDayUsingPivot(df.parse(day), pivotHour)); } public void assertEndOfPreviousDay(String day, String endOfDay) throws Exception { DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss.SSS"); assertEquals(df.parse(endOfDay), DateUtils.getEndOfDayBefore(df.parse(day))); } public void testEndOfDay() throws Exception { assertEndOfDayIs("24/03/2005 1:30:00.000", "24/03/2005 23:59:59.999"); assertEndOfDayIs("24/03/2005 22:30:00.000", "24/03/2005 23:59:59.999"); assertEndOfDayWithPivotHourIs(8, "24/03/2005 22:30:00.000", "24/03/2005 23:59:59.999"); assertEndOfDayWithPivotHourIs(8, "24/03/2005 8:30:00.000", "24/03/2005 23:59:59.999"); assertEndOfDayWithPivotHourIs(8, "24/03/2005 7:30:00.000", "23/03/2005 23:59:59.999"); assertEndOfPreviousDay("24/03/2005 7:30:00.000", "23/03/2005 23:59:59.999"); assertEndOfPreviousDay("24/03/2005 00:00:00.000", "23/03/2005 23:59:59.999"); assertEndOfPreviousDay("24/03/2005 23:59:59.999", "23/03/2005 23:59:59.999"); } public void testGetEndOfMonth() throws Exception { DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss.SSS"); Date endOfMonth = DateUtils.createEndOfMonth(df.parse("24/04/2005 1:30:00.000")); Calendar calendar = new GregorianCalendar(); calendar.setTime(endOfMonth); assertTrue(calendar.get(Calendar.DATE) == 30); } public void testGetStartUSAFinancialYear() { Date financialYearStart = DateUtils.createStartOfDay(2003, 12, 1); Date toDate = DateUtils.createStartOfDay(2003, 12, 4); assertEquals("Near beginning of financial year", financialYearStart, DateUtils.startOfUSAFinancialYearBefore(toDate)); toDate = DateUtils.createStartOfDay(2004, 8, 24); assertEquals("Middle of financial year", financialYearStart, DateUtils.startOfUSAFinancialYearBefore(toDate)); toDate = DateUtils.createStartOfDay(2004, 11, 30); assertEquals("Last day of financial year", financialYearStart, DateUtils.startOfUSAFinancialYearBefore(toDate)); toDate = DateUtils.createStartOfDay(2003, 12, 1); assertEquals("first day of financial", financialYearStart, DateUtils.startOfUSAFinancialYearBefore(toDate)); toDate = DateUtils.createStartOfDay(2005, 3, 1); assertEquals("Next Financial year", DateUtils.createStartOfDay(2004, 12, 1), DateUtils.startOfUSAFinancialYearBefore(toDate)); try { DateUtils.startOfUSAFinancialYearBefore((Date) null); fail("An Illegal Argument Exception should have been thrown: null date"); } catch (IllegalArgumentException iae) { // This should happen assertTrue(true); } } public void testGetStartOfMonth() { assertEquals(DateUtils.createStartOfDay(2005, 1, 1), DateUtils.getStartOfMonth(DateUtils.createStartOfDay(2005, 1, 17))); assertEquals(DateUtils.createStartOfDay(2004, 7, 1), DateUtils.getStartOfMonth(DateUtils.createStartOfDay(2004, 7, 1))); assertEquals(DateUtils.createStartOfDay(2004, 7, 1), DateUtils.getStartOfMonth(DateUtils.createStartOfDay(2004, 7, 8))); assertEquals(DateUtils.createStartOfDay(2004, 7, 1), DateUtils.getStartOfMonth(DateUtils.createStartOfDay(2004, 7, 28))); } public void testGetEndOfMonth2() { assertEquals(DateUtils.createStartOfDay(2005, 1, 31), DateUtils.getEndOfMonth(DateUtils.createStartOfDay(2005, 1, 17))); assertEquals(DateUtils.createStartOfDay(2005, 2, 28), DateUtils.getEndOfMonth(DateUtils.createStartOfDay(2005, 2, 15))); assertEquals(DateUtils.createStartOfDay(2004, 2, 29), DateUtils.getEndOfMonth(DateUtils.createStartOfDay(2004, 2, 15))); assertEquals(DateUtils.createStartOfDay(2004, 7, 31), DateUtils.getEndOfMonth(DateUtils.createStartOfDay(2004, 7, 8))); assertEquals(DateUtils.createStartOfDay(2004, 4, 30), DateUtils.getEndOfMonth(DateUtils.createStartOfDay(2004, 4, 28))); } public void testGetStartOfPreviousMonth() { assertEquals(DateUtils.createStartOfDay(2004, 12, 1), DateUtils.getStartOfPreviousMonth(DateUtils.createStartOfDay(2005, 1, 17))); assertEquals(DateUtils.createStartOfDay(2004, 6, 1), DateUtils.getStartOfPreviousMonth(DateUtils.createStartOfDay(2004, 7, 1))); assertEquals(DateUtils.createStartOfDay(2004, 6, 1), DateUtils.getStartOfPreviousMonth(DateUtils.createStartOfDay(2004, 7, 8))); assertEquals(DateUtils.createStartOfDay(2004, 6, 1), DateUtils.getStartOfPreviousMonth(DateUtils.createStartOfDay(2004, 7, 28))); } public void testGetEndOfPreviousMonth() { assertEquals(DateUtils.createStartOfDay(2004, 12, 31), DateUtils.getEndOfPreviousMonth(DateUtils.createStartOfDay(2005, 1, 17))); assertEquals(DateUtils.createStartOfDay(2005, 1, 31), DateUtils.getEndOfPreviousMonth(DateUtils.createStartOfDay(2005, 2, 15))); assertEquals(DateUtils.createStartOfDay(2004, 2, 29), DateUtils.getEndOfPreviousMonth(DateUtils.createStartOfDay(2004, 3, 15))); assertEquals(DateUtils.createStartOfDay(2004, 7, 31), DateUtils.getEndOfPreviousMonth(DateUtils.createStartOfDay(2004, 8, 8))); assertEquals(DateUtils.createStartOfDay(2004, 4, 30), DateUtils.getEndOfPreviousMonth(DateUtils.createStartOfDay(2004, 5, 28))); } public void testGetStartOfReportMonth() { assertEquals(DateUtils.createStartOfDay(2004, 12, 1), DateUtils.getReportStartOfMonth(DateUtils.createStartOfDay(2005, 1, 15))); assertEquals(DateUtils.createStartOfDay(2004, 6, 1), DateUtils.getReportStartOfMonth(DateUtils.createStartOfDay(2004, 7, 1))); assertEquals(DateUtils.createStartOfDay(2004, 7, 1), DateUtils.getReportStartOfMonth(DateUtils.createStartOfDay(2004, 7, 16))); assertEquals(DateUtils.createStartOfDay(2004, 7, 1), DateUtils.getReportStartOfMonth(DateUtils.createStartOfDay(2004, 7, 28))); } public void testGetEndOfReportMonth() { assertEquals(DateUtils.createStartOfDay(2004, 12, 31), DateUtils.getReportEndOfMonth(DateUtils.createStartOfDay(2005, 1, 15))); assertEquals(DateUtils.createStartOfDay(2005, 1, 31), DateUtils.getReportEndOfMonth(DateUtils.createStartOfDay(2005, 1, 16))); } public void testUSFinancialQuarter() { assertEquals(1, DateUtils.getStrictUSFYQuarter(DateUtils.createStartOfDay(2005, 12, 1))); assertEquals(4, DateUtils.getStrictUSFYQuarter(DateUtils.createStartOfDay(2005, 11, 1))); assertEquals(4, DateUtils.getStrictUSFYQuarter(DateUtils.createStartOfDay(2005, 11, 30))); } public void testUSFinancialYear() { assertEquals(2006, DateUtils.getFinancialYear(DateUtils.createStartOfDay(2005, 12, 1))); assertEquals(2007, DateUtils.getFinancialYear(DateUtils.createStartOfDay(2006, 12, 1))); } public void testMonth() { assertEquals(11, DateUtils.month(DateUtils.createStartOfDay(2005, 12, 1))); } public void testHalfYearlyStartDate() { Date halfYearlyStartdate = DateUtils.zeroOutTime(DateUtils.getHalfYearlyStartDate(DateUtils.createStartOfDay(2007, 01, 01))); assertEquals(DateUtils.zeroOutTime(DateUtils.createStartOfDay(2007, 01, 01)), halfYearlyStartdate); halfYearlyStartdate = DateUtils.zeroOutTime(DateUtils.getHalfYearlyStartDate(DateUtils.createStartOfDay(2007, 03, 11))); assertEquals(DateUtils.zeroOutTime(DateUtils.createStartOfDay(2007, 01, 01)), halfYearlyStartdate); halfYearlyStartdate = DateUtils.zeroOutTime(DateUtils.getHalfYearlyStartDate(DateUtils.createStartOfDay(2007, 06, 30))); assertEquals(DateUtils.zeroOutTime(DateUtils.createStartOfDay(2007, 01, 01)), halfYearlyStartdate); halfYearlyStartdate = DateUtils.zeroOutTime(DateUtils.getHalfYearlyStartDate(DateUtils.createStartOfDay(2007, 07, 1))); assertNotSame(DateUtils.zeroOutTime(DateUtils.createStartOfDay(2007, 01, 01)), halfYearlyStartdate); } public void testHalfYearlyEndDate() { Date halfYearlyEnddate = DateUtils.zeroOutTime(DateUtils.getHalfYearlyEndDate(DateUtils.createStartOfDay(2007, 07, 01))); assertEquals(DateUtils.zeroOutTime(DateUtils.createStartOfDay(2007, 12, 31)), halfYearlyEnddate); halfYearlyEnddate = DateUtils.zeroOutTime(DateUtils.getHalfYearlyEndDate(DateUtils.createStartOfDay(2007, 9, 11))); assertEquals(DateUtils.zeroOutTime(DateUtils.createStartOfDay(2007, 12, 31)), halfYearlyEnddate); halfYearlyEnddate = DateUtils.zeroOutTime(DateUtils.getHalfYearlyEndDate(DateUtils.createStartOfDay(2007, 12, 31))); assertEquals(DateUtils.zeroOutTime(DateUtils.createStartOfDay(2007, 12, 31)), halfYearlyEnddate); halfYearlyEnddate = DateUtils.zeroOutTime(DateUtils.getHalfYearlyEndDate(DateUtils.createStartOfDay(2007, 05, 01))); assertNotSame(DateUtils.zeroOutTime(DateUtils.createStartOfDay(2007, 07, 01)), halfYearlyEnddate); halfYearlyEnddate = DateUtils.zeroOutTime(DateUtils.getHalfYearlyEndDate(DateUtils.createStartOfDay(2007, 01, 31))); assertEquals(DateUtils.zeroOutTime(DateUtils.createStartOfDay(2007, 06, 30)), halfYearlyEnddate); halfYearlyEnddate = DateUtils.zeroOutTime(DateUtils.getHalfYearlyEndDate(DateUtils.createStartOfDay(2007, 03, 31))); assertEquals(DateUtils.zeroOutTime(DateUtils.createStartOfDay(2007, 06, 30)), halfYearlyEnddate); halfYearlyEnddate = DateUtils.zeroOutTime(DateUtils.getHalfYearlyEndDate(DateUtils.createStartOfDay(2007, 04, 30))); assertEquals(DateUtils.zeroOutTime(DateUtils.createStartOfDay(2007, 06, 30)), halfYearlyEnddate); } }
true
77a5570f42d582f065fb90bef049dd9e4c677dc2
Java
walkerwyl/ch2
/WEB-INF/classes/myservlet/DeleteServlet.java
UTF-8
2,508
2.3125
2
[]
no_license
package myservlet; import java.util.Iterator; import mybean.source_bean; import mybean.teacher_bean; import mybean.class_bean; import myservlet.DB; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; //@WebServlet(name="DeleteServlet", urlPatterns="/DeleteServlet") public class DeleteServlet extends HttpServlet{ public void init(ServletConfig config) throws ServletException{ super.init(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ HttpSession session = request.getSession(); teacher_bean teacher = (teacher_bean) session.getAttribute("TeacherBean"); String teaid = teacher.getTea_ID(); String couid = (String) request.getParameter("Cou_ID"); String souname = (String) request.getParameter("Sou_Name"); String deletePath = request.getServletContext().getRealPath( "/upload/" + teaid + "/" + couid + "/source/" + souname ); //首先从数据库中删除对应的数据,然后从老师资源库中删除对应的文件 try{ PreparedStatement ps; ps = DB.dbCon().prepareStatement("DELETE FROM source WHERE Sou_Name=?"); ps.setString(1,souname); ps.executeUpdate(); deleteFile(deletePath); //response.setContentType("text/html;charset=UTF-8"); //PrintWriter out = response.getWriter(); //out.println("<html><body>"); //out.println("Sou_Name=" + sou_name+ "的资源已删除"); //out.println(deletePath); //out.println("<a href=Tea_Homepage.jsp>回到教师主页面</a>"); //out.println("<a href=ManageFile.jsp>回到ManageFile.jsp页面</a>"); //out.println("</html></body>"); RequestDispatcher dispatcher = request.getRequestDispatcher("ManageFile.jsp?couid="+couid); dispatcher.forward(request, response); // response.getWriter().print("<script type='text/javascript' charset='UTF-8'>confirm(删除成功);windows.location='ManageFile.jsp?couid="+ couid +"'</script>"); } catch(Exception e){} // response.getWriter().print("<script type='text/javascript' charset='UTF-8'>confirm(删除成功);windows.location='ManageFile.jsp?couid="+ couid +"'</script>"); } public void deleteFile(String path){ File f = new File(path); f.delete(); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ doPost(request, response); } }
true
4ee6b50a0fdb2b523c6d4d0dc08fa45c9a72e836
Java
PanjiAD/MyCashBook
/app/src/main/java/com/project/mycashbook/PengeluaranActivity.java
UTF-8
4,303
2.15625
2
[]
no_license
package com.project.mycashbook; import androidx.appcompat.app.AppCompatActivity; import android.annotation.SuppressLint; import android.app.DatePickerDialog; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.ImageButton; import android.widget.TextView; import android.widget.Toast; import com.project.mycashbook.DataBase.DataBaseAccess; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Objects; public class PengeluaranActivity extends AppCompatActivity { Button simpan, kembali; EditText nominal, keterangan; ImageButton btntanggal; TextView tanggal; String tanggalIndo = ""; @SuppressLint("SimpleDateFormat") SimpleDateFormat sdfTanggalIndo = new SimpleDateFormat("dd-MM-yyyy"); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_pengeluaran); simpan = findViewById(R.id.simpan); kembali = findViewById(R.id.kembali); nominal = findViewById(R.id.nominal); keterangan = findViewById(R.id.keterangan); btntanggal = findViewById(R.id.btntanggal); tanggal = findViewById(R.id.tanggal); tanggalIndo = sdfTanggalIndo.format(new Date()); tanggal.setText(tanggalIndo); btntanggal.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final Calendar c = Calendar.getInstance(); int mYear = c.get(Calendar.YEAR); int mMonth = c.get(Calendar.MONTH); int mDay = c.get(Calendar.DAY_OF_MONTH); DatePickerDialog datePickerDialog = new DatePickerDialog(PengeluaranActivity.this, new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { try { tanggalIndo = sdfTanggalIndo.format(Objects.requireNonNull(sdfTanggalIndo.parse(dayOfMonth + "-" + (monthOfYear + 1) + "-" + year))); } catch (ParseException e) { e.printStackTrace(); } tanggal.setText(tanggalIndo); } }, mYear, mMonth, mDay); datePickerDialog.show(); } }); simpan.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(nominal.getText().toString().equals("") || keterangan.getText().toString().equals("")){ Toast.makeText(PengeluaranActivity.this, "Harap Lengkapi Data Anda", Toast.LENGTH_SHORT).show(); } else { Integer jumlah = Integer.valueOf(nominal.getText().toString()); DataBaseAccess dataBaseAccess = DataBaseAccess.getInstance(PengeluaranActivity.this); dataBaseAccess.open(); boolean isInserted = dataBaseAccess.insertMoney(jumlah, keterangan.getText().toString(), tanggal.getText().toString(), "outcome"); if(isInserted){ Toast.makeText(PengeluaranActivity.this, "Berhasil Memasukkan Pengeluaran", Toast.LENGTH_SHORT).show(); startActivity(new Intent(PengeluaranActivity.this, MenuActivity.class)); } else { Toast.makeText(PengeluaranActivity.this, "Gagal Memasukkan Pengeluaran", Toast.LENGTH_SHORT).show(); } } } }); kembali.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(PengeluaranActivity.this, MenuActivity.class)); } }); } @Override public void onBackPressed() { super.onBackPressed(); startActivity(new Intent(PengeluaranActivity.this, MenuActivity.class)); } }
true
75b0e5e123c282b1433f6be89a8ef6f257f714e1
Java
harshakshit97/CoffeeMachine
/CoffeeMachine-Harsh/src/main/java/com/example/CoffeeMachine/CoffeeMachineApplication.java
UTF-8
3,485
2.796875
3
[]
no_license
package com.example.CoffeeMachine; import com.example.CoffeeMachine.Model.Beverage; import com.example.CoffeeMachine.Model.Machine; import com.example.CoffeeMachine.thread.CoffeeMachineThread; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.locks.ReentrantLock; @SpringBootApplication public class CoffeeMachineApplication { public static void main(String[] args) { ApplicationContext ctx = SpringApplication.run(CoffeeMachineApplication.class, args); Config config = (Config) ctx.getBean("config"); Machine machine = (Machine) ctx.getBean("machine"); ReentrantLock reentrantLock = (ReentrantLock) ctx.getBean("reentrantLock"); //Less outlets than beverages with not enough ingredients for each beverage System.out.println(); System.out.println("************ Test Case 1 (when less outlets than beverages with not enough ingredients for each beverage) Started ************"); ExecutorService executorService = Executors.newFixedThreadPool(machine.getMachineOutlets()); for(Beverage beverage:machine.getBeverages()){ CoffeeMachineThread coffeeMachineThread = new CoffeeMachineThread(reentrantLock,machine,beverage); executorService.execute(coffeeMachineThread); } executorService.shutdown(); while(!executorService.isTerminated()){} //Less outlets than beverages with enough ingredients for each beverage System.out.println(); System.out.println("************ Test Case 2 (when less outlets than beverages with enough ingredients for each beverage) Started ************"); executorService = Executors.newFixedThreadPool(machine.getMachineOutlets()); machine.refillAllIngredients( 1000); machine.refillIngredient("green_mixture",100); System.out.println(); for(Beverage beverage:machine.getBeverages()){ CoffeeMachineThread coffeeMachineThread = new CoffeeMachineThread(reentrantLock,machine,beverage); executorService.execute(coffeeMachineThread); } executorService.shutdown(); while(!executorService.isTerminated()){} //Less outlets than beverages with enough ingredients for each beverage System.out.println(); System.out.println("************ Test Case 3 (when beverage orders are provided as list) Started ************"); executorService = Executors.newFixedThreadPool(machine.getMachineOutlets()); machine.refillIngredient("green_mixture",100); machine.refillIngredient("hot_water",100); System.out.println(); List<String> beveragesToPrepare = new ArrayList<>(Arrays.asList("hot_tea","hot_coffee","cold_coffee", "black_tea", "green_tea")); Map<String,Beverage> beverageMap = machine.prepareBeverageMap(); for(int i=0;i<beveragesToPrepare.size();i++){ if(!beverageMap.containsKey(beveragesToPrepare.get(i))) { System.out.println(beveragesToPrepare.get(i) + " cannot be prepared due to absence of required ingredients and recipe!!"); System.out.println(); continue; } CoffeeMachineThread coffeeMachineThread = new CoffeeMachineThread(reentrantLock,machine,beverageMap.get(beveragesToPrepare.get(i))); executorService.execute(coffeeMachineThread); } executorService.shutdown(); while(!executorService.isTerminated()){} } }
true
7552e688d5c9033a7246e0d55c5aac13e8fa3178
Java
manojk-ct/test
/src/main/java/com/zcon/mobileris/exceptions/FileUploadException.java
UTF-8
818
2.46875
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.zcon.mobileris.exceptions; /** * * @author zcon */ public class FileUploadException extends RuntimeException{ private String fileName; private String message; public FileUploadException(String fileName,String message) { this.fileName = fileName; this.message = message; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
true
69cc725a6559493f47bd4eba893c58fecb6a3efa
Java
jpsla94/ES1-2017-METIA1-44
/src/antiSpamFilter/AntiSpamFilterProblem.java
UTF-8
2,568
2.34375
2
[]
no_license
package antiSpamFilter; import java.util.ArrayList; import java.util.List; import org.uma.jmetal.problem.impl.AbstractDoubleProblem; import org.uma.jmetal.solution.DoubleSolution; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import pt.iscteiul.antispamfilter.models.AntiSpamMethods; import pt.iscteiul.antispamfilter.models.TipoFicheiro; import pt.iscteiul.antispamfilter.models.dao.DadosDao; public class AntiSpamFilterProblem extends AbstractDoubleProblem { public ObservableList<String> regras = FXCollections.observableArrayList(); public ObservableList<Double> pesosRegrasAuto = FXCollections.observableArrayList(); public String ficheiroSpam; public String ficheiroHam; private static final long serialVersionUID = 1L; public AntiSpamFilterProblem(ObservableList<String> regras, ObservableList<Double> pesosRegras, String ficheiroSpam, String ficheiroHam) { this(regras.size()); this.regras = regras; this.pesosRegrasAuto = pesosRegras; this.ficheiroSpam = ficheiroSpam; this.ficheiroHam = ficheiroHam; } public AntiSpamFilterProblem(Integer numberOfVariables) { setNumberOfVariables(numberOfVariables); setNumberOfObjectives(2); setName("AntiSpamFilterProblem"); List<Double> lowerLimit = new ArrayList<>(getNumberOfVariables()); List<Double> upperLimit = new ArrayList<>(getNumberOfVariables()); for (int i = 0; i < getNumberOfVariables(); i++) { lowerLimit.add(-5.0); upperLimit.add(5.0); } setLowerLimit(lowerLimit); setUpperLimit(upperLimit); } public void evaluate(DoubleSolution solution) { ObservableList<String> regraSpamAuto = FXCollections.observableArrayList(); ObservableList<String> regrasHamAuto = FXCollections.observableArrayList(); double[] fx = new double[getNumberOfObjectives()]; double[] x = new double[getNumberOfVariables()]; for (int i = 0; i < solution.getNumberOfVariables(); i++) { x[i] = solution.getVariableValue(i); } DadosDao dadosAutoSpam = new DadosDao(); dadosAutoSpam.lerFicheiro(ficheiroSpam, regraSpamAuto, pesosRegrasAuto, TipoFicheiro.Spam); AntiSpamMethods.calcularFpEFn(this.regras, regraSpamAuto, null, TipoFicheiro.Spam, fx, x); DadosDao dadosAutoHam = new DadosDao(); dadosAutoHam.lerFicheiro(ficheiroHam, regrasHamAuto, pesosRegrasAuto, TipoFicheiro.Ham); AntiSpamMethods.calcularFpEFn(this.regras, regrasHamAuto, null, TipoFicheiro.Ham, fx, x); solution.setObjective(0, fx[0]); solution.setObjective(1, fx[1]); } }
true
943503d3c5e31b679d14b367e4172cfce41b20ac
Java
aawajBhaukajee/SeniorDesign
/SeniorDesign/app/build/generated/data_binding_base_class_source_out/debug/out/com/example/seniordesign/databinding/MainToolbarBinding.java
UTF-8
1,412
2.09375
2
[]
no_license
// Generated by view binder compiler. Do not edit! package com.example.seniordesign.databinding; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.viewbinding.ViewBinding; import com.example.seniordesign.R; import java.lang.NullPointerException; import java.lang.Override; public final class MainToolbarBinding implements ViewBinding { @NonNull private final LinearLayout rootView; private MainToolbarBinding(@NonNull LinearLayout rootView) { this.rootView = rootView; } @Override @NonNull public LinearLayout getRoot() { return rootView; } @NonNull public static MainToolbarBinding inflate(@NonNull LayoutInflater inflater) { return inflate(inflater, null, false); } @NonNull public static MainToolbarBinding inflate(@NonNull LayoutInflater inflater, @Nullable ViewGroup parent, boolean attachToParent) { View root = inflater.inflate(R.layout.main_toolbar, parent, false); if (attachToParent) { parent.addView(root); } return bind(root); } @NonNull public static MainToolbarBinding bind(@NonNull View rootView) { if (rootView == null) { throw new NullPointerException("rootView"); } return new MainToolbarBinding((LinearLayout) rootView); } }
true
0faa3064b5f0286c20f5949310e071f6cf812ef6
Java
hragarwal/gameoflife
/src/main/java/com/gameoflife/Matrix.java
UTF-8
1,779
3.4375
3
[]
no_license
package com.gameoflife; import java.util.*; import static java.lang.Math.abs; import static java.lang.Math.max; import static java.lang.Math.min; public class Matrix { private List<Cell> cells; public Matrix(List<Cell> cells) { this.cells = cells; } public List<Cell> getCells() { return Collections.unmodifiableList(cells); } public Set<Cell> getNeigbours(Cell cell) { Set<Cell> neighbors = new HashSet<>(); int row = cell.getRow(); int col = cell.getCol(); neighbors.add(getCellAtPosition(min((abs(row - 1)) % 3, row), min((abs(col - 1)) % 3, col))); neighbors.add(getCellAtPosition(min((abs(row - 1)) % 3, row), col)); neighbors.add(getCellAtPosition(min((abs(row - 1)) % 3, row), max((abs(col + 1)) % 3, col))); neighbors.add(getCellAtPosition(row, min((abs(col - 1)) % 3, col))); neighbors.add(getCellAtPosition(row, max((abs(col + 1)) % 3, col))); neighbors.add(getCellAtPosition(max((abs(row + 1)) % 3, row), min((abs(col - 1)) % 3, col))); neighbors.add(getCellAtPosition(max((abs(row + 1)) % 3, row), col)); neighbors.add(getCellAtPosition(max((abs(row + 1)) % 3, row), max((abs(col + 1)) % 3, col))); neighbors.remove(getCellAtPosition(row, col)); return neighbors; } public long getLiveNeighboursCount(Cell cell) { return this.getNeigbours(cell) .stream() .filter(Cell::isAlive) .count(); } public Cell getCellAtPosition(int row, int col) { return cells.stream() .filter(cell -> row==cell.getRow() && col==cell.getCol()) .findFirst() .orElseThrow(IllegalArgumentException::new); } }
true
0aa142f7a4ec0dd51c1ec94e7200826c139d5b97
Java
Jam741/ModularizationProject
/baseywmj/src/main/java/com/yingwumeijia/baseywmj/entity/bean/UserBean.java
UTF-8
6,731
1.804688
2
[]
no_license
package com.yingwumeijia.baseywmj.entity.bean; import com.yingwumeijia.baseywmj.entity.UserSession; /** * Created by Jam * on 2016/6/1 17:49 * Describe: */ public class UserBean { /** * id : 0 * userName : * userPhone : * userType : * userTypeId : 0 * deleted : false * available : false * name : * gender : * mail : * idCard : * idImageA : * idImageB : * idHoldImage : * createUserId : 0 * createTime : * updateTime : * lastLoginTime : * entityId : 0 * nickName : * headImage : * showName : * showHead : */ private int userDetailType = 0; private int companyId; private String headImage; private String lifePhotos; private String resume; private int id; private String userName; private String userPhone; private String userType; private int userTypeId; private boolean deleted; private boolean available; private String name; private String gender; private String mail; private String idCard; private String idImageA; private String idImageB; private String idHoldImage; private int createUserId; private String createTime; private String updateTime; private String lastLoginTime; private int entityId; private String nickName; private String showName; private String userDetailTypeDesc; private String showHead; private String userTitle; private String imUid; private UserSession userSession; /*用户类型扩展,用于本地管理用户细分类型*/ private int userTypeExtension; public int getUserTypeExtension() { return userTypeExtension; } public void setUserTypeExtension(int userTypeExtension) { this.userTypeExtension = userTypeExtension; } public int getUserDetailType() { return userDetailType; } public void setUserDetailType(int userDetailType) { this.userDetailType = userDetailType; } public int getCompanyId() { return companyId; } public void setCompanyId(int companyId) { this.companyId = companyId; } public String getHeadImage() { return headImage; } public void setHeadImage(String headImage) { this.headImage = headImage; } public String getLifePhotos() { return lifePhotos; } public void setLifePhotos(String lifePhotos) { this.lifePhotos = lifePhotos; } public String getResume() { return resume; } public void setResume(String resume) { this.resume = resume; } public String getUserDetailTypeDesc() { return userDetailTypeDesc; } public void setUserDetailTypeDesc(String userDetailTypeDesc) { this.userDetailTypeDesc = userDetailTypeDesc; } public UserSession getUserSession() { return userSession; } public void setUserSession(UserSession userSession) { this.userSession = userSession; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserPhone() { return userPhone; } public void setUserPhone(String userPhone) { this.userPhone = userPhone; } public String getUserType() { return userType; } public void setUserType(String userType) { this.userType = userType; } public int getUserTypeId() { return userTypeId; } public void setUserTypeId(int userTypeId) { this.userTypeId = userTypeId; } public boolean isDeleted() { return deleted; } public void setDeleted(boolean deleted) { this.deleted = deleted; } public boolean isAvailable() { return available; } public void setAvailable(boolean available) { this.available = available; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getMail() { return mail; } public void setMail(String mail) { this.mail = mail; } public String getIdCard() { return idCard; } public void setIdCard(String idCard) { this.idCard = idCard; } public String getIdImageA() { return idImageA; } public void setIdImageA(String idImageA) { this.idImageA = idImageA; } public String getIdImageB() { return idImageB; } public void setIdImageB(String idImageB) { this.idImageB = idImageB; } public String getIdHoldImage() { return idHoldImage; } public void setIdHoldImage(String idHoldImage) { this.idHoldImage = idHoldImage; } public int getCreateUserId() { return createUserId; } public void setCreateUserId(int createUserId) { this.createUserId = createUserId; } public String getCreateTime() { return createTime; } public void setCreateTime(String createTime) { this.createTime = createTime; } public String getUpdateTime() { return updateTime; } public void setUpdateTime(String updateTime) { this.updateTime = updateTime; } public String getLastLoginTime() { return lastLoginTime; } public void setLastLoginTime(String lastLoginTime) { this.lastLoginTime = lastLoginTime; } public int getEntityId() { return entityId; } public void setEntityId(int entityId) { this.entityId = entityId; } public String getNickName() { return nickName; } public void setNickName(String nickName) { this.nickName = nickName; } public String getShowName() { return showName; } public void setShowName(String showName) { this.showName = showName; } public String getShowHead() { return showHead; } public void setShowHead(String showHead) { this.showHead = showHead; } public String getUserTitle() { return userTitle; } public void setUserTitle(String userTitle) { this.userTitle = userTitle; } public String getImUid() { return imUid; } public void setImUid(String imUid) { this.imUid = imUid; } }
true
aac8abbe245dc41602d0595305bd3e6ffff1f062
Java
sjh010/ImageConverter
/ImageDaemon/src/main/java/com/mobileleader/image/deamon/ConvertDaemon.java
UTF-8
6,760
1.882813
2
[]
no_license
package com.mobileleader.image.deamon; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.concurrent.PriorityBlockingQueue; import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.stereotype.Component; import org.springframework.util.ObjectUtils; import com.google.gson.Gson; import com.mobileleader.image.data.dto.ConvertStatus; import com.mobileleader.image.data.mapper.ConvertStatusMapper; import com.mobileleader.image.model.ConvertRequest; import com.mobileleader.image.model.ConvertResponse; import com.mobileleader.image.service.ImageConvertService; import com.mobileleader.image.socket.client.ImageConvertOutboundClient; import com.mobileleader.image.type.JobType; import com.mobileleader.image.type.ResponseCodeType; import com.mobileleader.image.util.JsonUtils; import com.mobileleader.image.util.TimeLogUtils; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.util.CharsetUtil; import lombok.extern.slf4j.Slf4j; @Slf4j @Component public class ConvertDaemon { @Autowired @Qualifier("convertExecutor") private ThreadPoolTaskExecutor convertExecutor; // thread pool 관리를 위한 executor @Autowired private ImageConvertService imageConvertService; // 이미지 변환 담당 서비스 @Autowired private ConvertStatusMapper convertStatusMapper; // 배치 변환 요청 상태 매퍼 @Autowired private ImageConvertOutboundClient imageConvertOutboundClient; // 배치 요청 응답을 위한 client // private PriorityQueue<ConvertRequest> requestQueue; // 이미지 변환 요청 큐(우선순위 큐) private PriorityBlockingQueue<ConvertRequest> requestQueue; // 이미지 변환 요청 큐(우선순위 큐) private Map<String, ChannelFuture> channelFutureMap; // 이미지 요청 JOB ID별 응답을 위한 ChannelFuture Map public ConvertDaemon() { this.requestQueue = new PriorityBlockingQueue<ConvertRequest>(); this.channelFutureMap = new HashMap<String, ChannelFuture>(); } /** * 이미지 변환 중에 데몬이 비정상 종료 되었을 경우, * 데몬 재기동 시에 비정상 종료 전 이미지 변환 작업에 대한 실패 응답 전송 */ @PostConstruct public void sendConvertFailResponse() { List<ConvertStatus> statusList = convertStatusMapper.selectConvertFailList(); if (!ObjectUtils.isEmpty(statusList)) { for (ConvertStatus status : statusList) { ConvertResponse response = new ConvertResponse(); response.setJobId(status.getJobId()); response.setResponseCode(ResponseCodeType.SHUTDOWN_DAEMON.getCode()); imageConvertOutboundClient.sendResponse(response); convertStatusMapper.deleteBatchConvertStatus(status.getJobId()); } } } /** * 이미지 변환 작업에 사용할 Thread 개수 변경 */ public void changeCoreThreadCount(int threadChangeCount) { log.info("Change thread count : {} -> {}", convertExecutor.getCorePoolSize(), threadChangeCount); convertExecutor.setCorePoolSize(threadChangeCount); convertExecutor.setMaxPoolSize(threadChangeCount); log.info("Thread core pool size : {}", convertExecutor.getCorePoolSize()); } /** * 이미지 변환 요청을 이미지 변환 요청 큐에 삽입 후, 변환 작업 수행 */ public void addRequest(ConvertRequest request, ChannelFuture channelFuture) { log.info("[{}] add to Queue", request.getJobId()); this.requestQueue.add(request); this.channelFutureMap.put(request.getJobId(), channelFuture); if (JobType.BATCH.getCode().equalsIgnoreCase(request.getJobType())) { // DB ConvertStatus convertStatus = new ConvertStatus(); convertStatus.setFilePath(request.getSrcPath()); convertStatus.setJobId(request.getJobId()); long startTime = System.currentTimeMillis(); convertStatusMapper.insertBatchConvertRequest(convertStatus); TimeLogUtils.logging(startTime, System.currentTimeMillis(), "[" + request.getJobId() +"] DB insert"); } process(); } /** * 이미지 변환 수행 */ private void process() { // 이미지 변환 요청에 Queue에 쌓여 있는지 확인 if (!requestQueue.isEmpty()) { convertExecutor.execute(new Runnable() { @Override @Async public void run() { ConvertRequest request = requestQueue.poll(); log.info("Request : {}", JsonUtils.ObjectPrettyPrint(request)); ChannelFuture channelFuture = channelFutureMap.get(request.getJobId()); long startTime = System.currentTimeMillis(); ConvertResponse response = imageConvertService.convert(request); // 이미지 변환 response.setDesRootPath(request.getDesRootPath()); TimeLogUtils.logging(startTime, System.currentTimeMillis(), "[" + request.getJobId() + "] Convert image"); if (JobType.REALTIME.getCode().equalsIgnoreCase(request.getJobType())) { // 실시간 요청 try { startTime = System.currentTimeMillis(); channelFuture.channel().writeAndFlush(Unpooled.copiedBuffer(new Gson().toJson(response), CharsetUtil.UTF_8)); channelFuture.addListener(ChannelFutureListener.CLOSE); TimeLogUtils.logging(startTime, System.currentTimeMillis(), "[" + request.getJobId() + "] Send response (R)"); } catch (Exception e) { log.error("Error", e); channelFuture.addListener(ChannelFutureListener.CLOSE); } } else if (JobType.BATCH.getCode().equalsIgnoreCase(request.getJobType())) { // 배치 요청 try { startTime = System.currentTimeMillis(); imageConvertOutboundClient.sendResponse(response); TimeLogUtils.logging(startTime, System.currentTimeMillis(), "[" + request.getJobId() + "] Send response (B)"); startTime = System.currentTimeMillis(); convertStatusMapper.deleteBatchConvertStatus(request.getJobId()); TimeLogUtils.logging(startTime, System.currentTimeMillis(), "[" + request.getJobId() + "] DB delete"); } catch (Exception e) { e.printStackTrace(); } } else { channelFuture.channel().writeAndFlush(Unpooled.EMPTY_BUFFER); channelFuture.addListener(ChannelFutureListener.CLOSE); } } }); } } }
true
4d85c91be4d7b87b7324ddd27bf17908ae653cc7
Java
adarbayan/KUVID302
/src/Domain/Atoms.java
UTF-8
1,342
2.40625
2
[]
no_license
package Domain; import java.util.ArrayList; public interface Atoms { public static final double alphaStability = 0.85; public static final double betaStability = 0.9; public static final double gammaStability = 0.8; public static final double sigmaStability = 0.7; public static final int alphaProton = 8; public static final int betaProton = 16; public static final int gammaProton = 32; public static final int sigmaProton = 64; public ArrayList<ShieldDecorator> shields = new ArrayList<ShieldDecorator>(); public double calculateEfficiency(); public String getType(); public int getxPos(); public void setxPos(int xPos); public int getyPos(); public void setyPos(int yPos); public int getWidth(); public void setWidth(int width); public int getLength(); public void setLength(int length); public int getNeutron(); public void setNeutron(int neutron); public int getProton(); public void setProton(int proton); public double getEfficiency(); public void setEfficiency(double efficiency); public double getxSpeed(); public void setxSpeed(double xSpeed) ; public double getySpeed(); public void setySpeed(double ySpeed); public ArrayList<ShieldDecorator> getShields(); public void setShields(ArrayList<ShieldDecorator> s); public void addShields(int i); }
true
2a3371d6936d1b5b6876514cf54662e1d3b0a52a
Java
hahava/Right-Hand
/src/main/java/com/righthand/board/dto/model/BoardDetailVO.java
UTF-8
116
1.546875
2
[]
no_license
package com.righthand.board.dto.model; import lombok.Data; @Data public class BoardDetailVO { int boardSeq; }
true
4bb56a88f34cebd62fa7961e2e1367db0b67019e
Java
thwe/javaOCP
/day21/Loesungen/Pizza_Schweiger/PizzaAufgabe/Topping.java
UTF-8
368
2.90625
3
[]
no_license
package PizzaAufgabe; public abstract class Topping implements Pizza{ private final Pizza below; // private int price; public Topping(Pizza pizza){ this.below = pizza; } // public int getPrice(){ // price = this.price + below.getPrice(); // return price; // } // // public void setPrice(int price){ // this.price = price; // } }
true
14f21be87b4179070e8b8ff6f43b558b677846be
Java
SlobodanPrijic/nfc-helper-android-java
/nfchelper/src/main/java/com/hyperether/nfchelper/NfcUtil.java
UTF-8
5,681
2.140625
2
[]
no_license
package com.hyperether.nfchelper; import android.content.Intent; import android.nfc.NdefMessage; import android.nfc.NdefRecord; import android.nfc.NfcAdapter; import android.nfc.Tag; import android.os.Parcelable; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.util.Locale; import static android.nfc.NdefRecord.createMime; /** * Created by Slobodan on 7/17/2017. */ public class NfcUtil { public static final String UNLOCK_CHECK = "check_unlock"; public static final String PAYLOAD_UNLOCK = "unlock"; public static final String PAYLOAD_NOTHING = "nothing"; /* <intent-filter> <action android:name="android.nfc.action.NDEF_DISCOVERED" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="text/plain" /> </intent-filter> */ public NdefRecord createTextRecord(String payload, boolean encodeInUtf8) { Locale locale = Locale.getDefault(); byte[] langBytes = locale.getLanguage().getBytes(Charset.forName("US-ASCII")); Charset utfEncoding = encodeInUtf8 ? Charset.forName("UTF-8") : Charset.forName("UTF-16"); byte[] textBytes = payload.getBytes(utfEncoding); int utfBit = encodeInUtf8 ? 0 : (1 << 7); char status = (char) (utfBit + langBytes.length); byte[] data = new byte[1 + langBytes.length + textBytes.length]; data[0] = (byte) status; System.arraycopy(langBytes, 0, data, 1, langBytes.length); System.arraycopy(textBytes, 0, data, 1 + langBytes.length, textBytes.length); NdefRecord record = new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], data); return record; } /* <intent-filter> <action android:name="android.nfc.action.NDEF_DISCOVERED" /> <category android:name="android.intent.category.DEFAULT" /> <data android:scheme="http" android:host="example.com" android:pathPrefix="" /> </intent-filter> */ public NdefRecord createNdefRecordUri(String uriString) { return NdefRecord.createUri(uriString); } public NdefRecord createNdefRecordMime(String payload) { return NdefRecord.createMime("application/vnd.com.example.android.beam", payload.getBytes(Charset.forName("US-ASCII"))); } public NdefRecord createNdefRecordMime2(String payload) { return new NdefRecord( NdefRecord.TNF_MIME_MEDIA, "application/vnd.com.example.android.beam".getBytes(Charset.forName("US-ASCII")), new byte[0], payload.getBytes(Charset.forName("US-ASCII"))); } public NdefMessage createNdefMessage1(String payload) { NdefMessage msg = new NdefMessage( new NdefRecord[]{createMime( "application/vnd.com.example.android.beam", payload.getBytes()) /** * The Android Application Record (AAR) is commented out. When a device * receives a push with an AAR in it, the application specified in the AAR * is guaranteed to run. The AAR overrides the tag dispatch system. * You can add it back in to guarantee that this * activity starts when receiving a beamed message. For now, this code * uses the tag dispatch system. */ //, NdefRecord.createApplicationRecord("com.example.android.beam") }); return msg; } public NdefMessage createNdefMessage2(String payload) { return new NdefMessage(new NdefRecord[]{createTextRecord(payload, true)}); } public NdefMessage createNdefMessageUri(String payload) { return new NdefMessage(new NdefRecord[]{createNdefRecordUri(payload)}); } public NdefMessage createNdefMessageMime(String payload) { return new NdefMessage(new NdefRecord[]{createNdefRecordMime(payload)}); } public NdefMessage createNdefMessageMime2(String payload) { return new NdefMessage(new NdefRecord[]{createNdefRecordMime2(payload)}); } public void parseNfc(Intent intent, NfcParser callback) { if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) { Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) { Parcelable[] rawMessages = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES); if (rawMessages != null) { NdefMessage[] messages = new NdefMessage[rawMessages.length]; for (int i = 0; i < rawMessages.length; i++) { messages[i] = (NdefMessage) rawMessages[i]; } // Process the messages array. String txtReceived = ""; NdefRecord firstRecord = messages[0].getRecords()[0]; byte[] payload = firstRecord.getPayload(); byte[] data = new byte[payload.length - 3]; System.arraycopy(payload, 3, data, 0, data.length); try { txtReceived = new String(data, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } if (callback != null) callback.onPayloadParsed(txtReceived); } } } } }
true
2a95cdbaf02b476439b455a20a35473823c8cf79
Java
koziolek151815/social-site-backend
/src/main/java/com/socialsitebackend/socialsite/post/PostFactory.java
UTF-8
2,449
2.421875
2
[]
no_license
package com.socialsitebackend.socialsite.post; import com.socialsitebackend.socialsite.entities.ImageEntity; import com.socialsitebackend.socialsite.entities.PostEntity; import com.socialsitebackend.socialsite.entities.TagEntity; import com.socialsitebackend.socialsite.entities.UserEntity; import com.socialsitebackend.socialsite.post.dto.AddPostDto; import com.socialsitebackend.socialsite.post.dto.BasicPostInfoDto; import com.socialsitebackend.socialsite.post.dto.PostResponseDto; import com.socialsitebackend.socialsite.user.UserFactory; import lombok.RequiredArgsConstructor; import java.time.Instant; import java.util.Set; import java.util.stream.Collectors; @RequiredArgsConstructor public class PostFactory { private final UserFactory userFactory; public PostResponseDto entityToResponseDto(PostEntity entity) { return PostResponseDto.builder() .postId(entity.getId()) .description(entity.getDescription()) .postPhotoName(entity.getPostPhoto()==null?null:entity.getPostPhoto().getOriginalFilename()) .postCreatedDate(entity.getPostCreatedDate()) .title(entity.getTitle()) .postAuthor(userFactory.entityToBasicUserProfileInfoDto(entity.getAuthor())) .parentPost(this.entityToBasicPostInfoDto(entity.getParentPost())) .rating(entity.getVotes() == null ? 0 : entity.getVotes().stream().map(vote -> vote.getRating() ? 1 : -1).reduce(0, Integer::sum)) .tags(entity.getTags().stream().map(tag->tag.getTagName()).collect(Collectors.toList())) .build(); } public PostEntity addPostDtoToEntity(AddPostDto dto, UserEntity postAuthor, PostEntity parentPost, Set<TagEntity> tags, ImageEntity image) { return PostEntity.builder() .title(dto.getTitle()) .tags(tags) .description(dto.getDescription()) .postPhoto(image) .postCreatedDate(Instant.now()) .author(postAuthor) .parentPost(parentPost) .build(); } public BasicPostInfoDto entityToBasicPostInfoDto(PostEntity post){ if (post == null) return null; return BasicPostInfoDto.builder() .postId(post.getId()) .title(post.getTitle()) .build(); } }
true
d41775c7eadeb0bef770050b2a35bb4d804bf0d2
Java
zhaokangjin/flat
/paas/paas_portal/src/main/java/com/flat/paas/portal/domain/Enterprise.java
UTF-8
2,924
1.9375
2
[]
no_license
package com.flat.paas.portal.domain; import java.util.Date; public class Enterprise { // 用户ID >>>表字段 : USER_ID private String userId; // 用户类别 >>>表字段 : USER_CATEGORY private String userCategory; // 角色ID >>>表字段 : ROLE_ID private String roleId; // 权限ID >>>表字段 : PERMISSION_ID private String permissionId; // 资源组ID >>>表字段 : RESOURCES_GROUP_ID private String resourcesGroupId; // 密码 >>>表字段 : PASSWORD private String password; // 原密码 >>>表字段 : ORIGINAL_PASSWORD private String originalPassword; // 删除标记 >>>表字段 : DELETE_FLAG private String deleteFlag; // 创建时间 >>>表字段 : CREATE_TIME private Date createTime; // 生效时间 >>>表字段 : ENABLE_TIME private Date enableTime; // 失效时间 >>>表字段 : DISABLE_TIME private Date disableTime; public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getUserCategory() { return userCategory; } public void setUserCategory(String userCategory) { this.userCategory = userCategory; } public String getRoleId() { return roleId; } public void setRoleId(String roleId) { this.roleId = roleId; } public String getPermissionId() { return permissionId; } public void setPermissionId(String permissionId) { this.permissionId = permissionId; } public String getResourcesGroupId() { return resourcesGroupId; } public void setResourcesGroupId(String resourcesGroupId) { this.resourcesGroupId = resourcesGroupId; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getOriginalPassword() { return originalPassword; } public void setOriginalPassword(String originalPassword) { this.originalPassword = originalPassword; } public String getDeleteFlag() { return deleteFlag; } public void setDeleteFlag(String deleteFlag) { this.deleteFlag = deleteFlag; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getEnableTime() { return enableTime; } public void setEnableTime(Date enableTime) { this.enableTime = enableTime; } public Date getDisableTime() { return disableTime; } public void setDisableTime(Date disableTime) { this.disableTime = disableTime; } }
true
9ef8da286a2beaabfb9a1fab870dc9fd18617b6d
Java
macrotea/macrotea-hibernate-manytomanty-anno
/src/main/java/com/mtea/mhmtm/entity/DispatchWorkOrderEntity.java
UTF-8
1,312
2.0625
2
[]
no_license
/* * Copyright(C) 2013 Thunderfox ALL Rights Reserved */ package com.mtea.mhmtm.entity; import java.util.Date; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; /** * @author macrotea@qq.com * @version 1.0 * @date 2013-8-12 下午20:17:23 * @note */ @Entity @Table(name="tb_dispatch_work_order") public class DispatchWorkOrderEntity { @Id @GeneratedValue private Long id; /** * 派工时间 */ private Date dispatchTime; /** * 备注 */ private String remark; /** * 工单处理用户 */ private String orderHandleUser; /** * */ public DispatchWorkOrderEntity() { super(); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Date getDispatchTime() { return dispatchTime; } public void setDispatchTime(Date dispatchTime) { this.dispatchTime = dispatchTime; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public String getOrderHandleUser() { return orderHandleUser; } public void setOrderHandleUser(String orderHandleUser) { this.orderHandleUser = orderHandleUser; } }
true
aeab982eb2d7c7f19202e9bb826e0f59a4b23516
Java
pavlentytest/Generics-3group
/src/com/company/Main.java
UTF-8
570
2.640625
3
[]
no_license
package com.company; import java.util.ArrayList; public class Main { public static void main(String[] args) { ArrayList persons = new ArrayList(); //20 persons.add(1); persons.add("Test"); persons.add(new Object()); int a = (int)persons.get(1); ArrayList<Integer> bbb = new ArrayList<>(); bbb.add(1); bbb.add(90); // bbb.add("Heee"); Account<Integer,Double> acc1 = new Account<>(12312,(double)90000); Account<String,Integer> acc2 = new Account<>("B3939",45454); } }
true
170ee0a1de37b8680ae0b63e1ef7e74beb25214e
Java
liaoxianghua/tsjx
/src/main/java/cn/com/tsjx/user/task/UserTask.java
UTF-8
483
2.09375
2
[]
no_license
package cn.com.tsjx.user.task; import javax.annotation.Resource; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import cn.com.tsjx.user.service.UserService; @Component public class UserTask { @Resource UserService userService; /** * 自动删除未及时激活的注册用户 */ @Scheduled(cron="0 0/10 * * * ? ") //间隔10分钟执行 public void autoDeteleUser() { userService.autoDeteleUser(); } }
true
45f6d7b45da4f757ecb2aa8be924ff3629851bf4
Java
Amelie1992/maomi
/.svn/pristine/45/45f6d7b45da4f757ecb2aa8be924ff3629851bf4.svn-base
UTF-8
1,777
1.992188
2
[]
no_license
/** * Copyright (C) 2017 FZJT Co. Ltd. * * * @className:com.xed.financing.wxgzh.service.pay.PayExportInfoService * @description: * * @version:v1.0.0 * @author:Qian Tao * * Modification History: * Date Author Version Description * ----------------------------------------------------------------- * 2017年5月26日 Qian Tao v1.0.0 create * * */ package com.xed.financing.wxgzh.service.pay; import java.sql.SQLException; import java.util.List; import com.xed.financing.wxgzh.model.pay.PayExportInfoBean; /** * @className:com.xed.financing.wxgzh.service.pay.PayExportInfoService * @description: * @version:v1.0.0 * @date:2017年5月26日 下午1:58:08 * @author:Qian Tao */ public interface PayExportInfoService { /** * 保存 * * @Description: * @param payExportInfoBean * @throws SQLException * @version:v1.0 * @author:Qian Tao * @date:2017年5月26日 下午1:55:05 */ public int savePayExport(PayExportInfoBean payExportInfoBean) throws SQLException; /** * 修改错误代码 * * @Description: * @param payExportInfoBean * @throws SQLException * @version:v1.0 * @author:Qian Tao * @date:2017年5月27日 上午11:09:07 */ public boolean updatePayExportStatus(PayExportInfoBean payExportInfoBean) throws SQLException; /** * * @Description:查找 * @return * @throws SQLException * @version:v1.0 * @author:WangJun * @date:2017年5月27日 下午3:47:42 */ public List<PayExportInfoBean> queryPayExportAll() throws SQLException; public String queryAccountId(PayExportInfoBean payExportInfoBean) throws SQLException; public Boolean toPayExport(String telephones,String amt)throws Exception; }
true
083dcaeefdb1269ba245f34df130cf13745e04d0
Java
MiracleWhy/TEST
/CarsokAPI-login/src/main/java/com/uton/carsokApi/controller/request/SetPayPwdRequest.java
UTF-8
318
1.875
2
[]
no_license
package com.uton.carsokApi.controller.request; /** * 设置支付密码 * @author bing.cheng * */ public class SetPayPwdRequest { private String payPassword; public String getPayPassword() { return payPassword; } public void setPayPassword(String payPassword) { this.payPassword = payPassword; } }
true
151dca7d4a96be75ab96192d0f70bbca74ea6443
Java
charlieskc/RequestForQuoteWebService
/src/main/java/com/leon/ws/rfq/events/NewSearchCriterionEvent.java
UTF-8
957
2.1875
2
[]
no_license
package com.leon.ws.rfq.events; import org.springframework.context.ApplicationEvent; import com.google.gson.Gson; import com.leon.ws.rfq.search.SearchCriterionImpl; @SuppressWarnings("serial") public final class NewSearchCriterionEvent extends ApplicationEvent implements JsonSerializableEvent { private final SearchCriterionImpl newCriterion; private static final String NEW_CRITERION_UPDATE = "NewCriterionUpdate"; public NewSearchCriterionEvent(Object source, SearchCriterionImpl newCriterion) { super(source); this.newCriterion = newCriterion; } @Override public String toString() { return "New criterion event: " + this.newCriterion; } public SearchCriterionImpl getNewCriterion() { return this.newCriterion; } @Override public String getJson() { return new Gson().toJson(this.newCriterion); } @Override public String getMessageType() { return NEW_CRITERION_UPDATE; } }
true
133f51e9aabe40c1f33272a36662be4b0b63aa0d
Java
zzp15222522401/daima
/workspace/day11/src/com/shangguigu/demo/demo1/Test4.java
UTF-8
293
1.921875
2
[]
no_license
package com.shangguigu.demo.demo1; public class Test4 { public static void main(String[] args) { Rabbit rabbit=new Rabbit(); WangBa wangBa=new WangBa(); rabbit.run(); System.out.println("***********"); wangBa.run(); wangBa.swim(); } }
true
4d1d520232379423f011a50ece47d548b377789b
Java
vsuraj3/Leetcode
/Fisrt_Unique_Char.java
UTF-8
545
3.390625
3
[]
no_license
class Solution { public int firstUniqChar(String s) { HashMap<Character, Integer> h1 = new HashMap<Character, Integer>(); for(int i=0;i<s.length();i++) { char curr=s.charAt(i); if(!h1.containsKey(curr)) { h1.put(curr, i); } else { h1.put(curr, -1); } } int min=Integer.MAX_VALUE; for(char c:h1.keySet()) { if(h1.get(c)>-1 && h1.get(c)<min) { min=h1.get(c); } } return min==Integer.MAX_VALUE?-1:min; } }
true
45afdb41d42d7cee222e0fc95f84e7c93d2277b0
Java
springTeacher/java-learnning
/src/main/java/com/xiaoniu/jdk/StringUtils.java
UTF-8
533
2.46875
2
[]
no_license
package com.xiaoniu.jdk; import java.util.*; import java.util.stream.Collectors; /** * * * @author lihoujing * @date 2019/10/8 10:12 */ public class StringUtils { public static void main(String[] args) { Integer[] arr = {1,4,76,8,9,5,3,3}; List<Integer> list = new ArrayList<>(); list.add(23); Iterator<Integer> iterator = list.iterator(); while (iterator.hasNext()){ Integer next = iterator.next(); iterator.remove(); } } }
true
3d324a1b7795ea456374f77227683280f1f1fa3c
Java
AbdoHerO/exercises-exams
/JAVA/MyDateExercise/exceptions/NoMonthException.java
UTF-8
276
2.4375
2
[]
no_license
package main.exceptions; /** * Created by yassine on 2/22/17. */ public class NoMonthException extends Exception{ /** * */ private static final long serialVersionUID = 1L; public String getMessage(){ return "There is no such month in the year"; } }
true
e78cbf5fc60524442156ef9b54e5d22cff864d12
Java
chriskriel/kwami
/kwami-pathsend-utils/src/main/java/net/kwami/pathsend/ParameterBuffer.java
UTF-8
5,984
2.5
2
[]
no_license
package net.kwami.pathsend; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.util.HashMap; import java.util.Map; import java.util.Set; import net.kwami.utils.MyProperties; public final class ParameterBuffer { public static final short HDR_LEN = 10; private static final int LEN1_OFFSET = 4; private static final int LEN2_OFFSET = 6; private static final int MSG_ID_OFFSET = 8; private static final byte TERMINATOR = 0; private static final int MAX_NAME = 512; private int size = Short.MAX_VALUE / 16; private ByteBuffer bb = null; private Map<String, Integer> keys = null; public final static ParameterBuffer wrap(byte[] bytes) { return wrap(bytes, 0, bytes.length); } public final static ParameterBuffer wrap(byte[] bytes, int offset, int length) { ParameterBuffer obj = new ParameterBuffer(); obj.bb = ByteBuffer.wrap(bytes, offset, length); obj.position(length); return obj; } private ParameterBuffer() { } public ParameterBuffer(int msgId) { bb = ByteBuffer.allocate(size); initialize(msgId); } public ParameterBuffer(int msgId, int size) { this.size = size; bb = ByteBuffer.allocate(size); initialize(msgId); } public final ParameterBuffer initialize(int newMsgId, MyProperties parameters) { initialize(newMsgId); for (String name : parameters.stringPropertyNames()) { addParameter(name, parameters.getProperty(name, ""), true); } return this; } public final ParameterBuffer initialize(int newMsgId) { short shortMsgId = Short.parseShort(String.valueOf(newMsgId)); if (keys == null) keys = new HashMap<String, Integer>(); keys.clear(); bb.clear(); bb.putInt(0); bb.position(MSG_ID_OFFSET); bb.putShort(shortMsgId); return this; } public final int position() { return bb.position(); } public final void position(int pos) { bb.position(pos); if (pos > HDR_LEN) { int dataLen = bb.position() - HDR_LEN; bb.putShort(LEN1_OFFSET, (short) dataLen); bb.putShort(LEN2_OFFSET, (short) dataLen); } keyMap(this); } public final byte[] array() { if (bb == null) return null; position(bb.position()); return bb.array(); } public final int getMsgId() { if (bb == null) return 0; return bb.getShort(8); } public final ParameterBuffer addParameter(String name, byte value) throws UnsupportedEncodingException { setParameterName(name); bb.putShort((short) (Byte.SIZE / Byte.SIZE)); bb.put(value); return this; } public final ParameterBuffer addParameter(String name, short value) throws UnsupportedEncodingException { setParameterName(name); bb.putShort((short) (Short.SIZE / Byte.SIZE)); bb.putShort(value); return this; } public final ParameterBuffer addParameter(String name, int value) throws UnsupportedEncodingException { bb.put(name.getBytes()); bb.put(TERMINATOR); bb.putShort((short) (Integer.SIZE / Byte.SIZE)); bb.putInt(value); return this; } public final ParameterBuffer addParameter(String name, long value) throws UnsupportedEncodingException { setParameterName(name); bb.putShort((short) (Long.SIZE / Byte.SIZE)); bb.putLong(value); return this; } public final ParameterBuffer addParameter(String name, byte[] value) throws UnsupportedEncodingException { return addParameter(name, value, 0, (short) value.length); } public final ParameterBuffer addParameter(String name, byte[] value, int offset, short length) throws UnsupportedEncodingException { setParameterName(name); bb.putShort(length); bb.put(value, offset, length); return this; } public final ParameterBuffer addParameter(String name, String value, boolean addNullTerminator) { if (value == null) return this; setParameterName(name); bb.putShort((short) (value.length() + (addNullTerminator ? 1 : 0))); if (value.length() > 0) { bb.put(value.getBytes()); } if (addNullTerminator) bb.put(TERMINATOR); return this; } public final Set<String> keySet() { return keys.keySet(); } public final byte getByteValue(String name) { if (keys.get(name) == null) return 0; return bb.get(keys.get(name) + 2); } public final short getShortValue(String name) { if (keys.get(name) == null) return 0; return bb.getShort(keys.get(name) + 2); } public final int getIntValue(String name) { if (keys.get(name) == null) return 0; return bb.getInt(keys.get(name) + 2); } public final long getLongValue(String name) { if (keys.get(name) == null) return 0; return bb.getLong(keys.get(name) + 2); } public final byte[] getByteArrayValue(String name) { if (keys.get(name) == null) return null; byte[] valueBytes = null; int valuePosition = keys.get(name); int putPosition = bb.position(); bb.position(valuePosition); int valueLen = bb.getShort(); if (valueLen > 0) { valueBytes = new byte[valueLen]; bb.get(valueBytes); } bb.position(putPosition); return valueBytes; } public final String getStringValue(String name) { byte[] valueBytes = getByteArrayValue(name); if (valueBytes == null) return ""; return (new String(valueBytes)).trim(); } public final ParameterBuffer extractPropertiesInto(MyProperties parameters) { for (String key : keySet()) { parameters.setProperty(key, getStringValue(key)); } return this; } private final void setParameterName(String name) { bb.put(name.getBytes()); bb.put(TERMINATOR); keys.put(name, bb.position()); } private final static void keyMap(ParameterBuffer me) { if (me.keys == null) me.keys = new HashMap<String, Integer>(); me.keys.clear(); int length = me.bb.getShort(LEN1_OFFSET) + HDR_LEN; byte[] nameBytes = new byte[MAX_NAME]; int j = 0, i = HDR_LEN; for (; i < length; i++) { byte b = me.bb.get(i); if (b != TERMINATOR) { nameBytes[j++] = b; continue; } me.keys.put((new String(nameBytes)).trim(), ++i); nameBytes = new byte[MAX_NAME]; j = 0; i += me.bb.getShort(i) + 1; } return; } }
true
0eb15f2d4da34036867b1c2ea028b024f11e928f
Java
hoyoungmoon/android-management-application
/app/src/main/java/com/project/realproject/activities/CalculatorActivity.java
UTF-8
2,406
2.015625
2
[]
no_license
package com.project.realproject.activities; import android.os.Bundle; import android.view.View; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import androidx.viewpager.widget.ViewPager; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdView; import com.google.android.gms.ads.MobileAds; import com.google.android.gms.ads.initialization.InitializationStatus; import com.google.android.gms.ads.initialization.OnInitializationCompleteListener; import com.google.android.material.tabs.TabLayout; import com.kakao.adfit.ads.ba.BannerAdView; import com.project.realproject.R; import com.project.realproject.adapters.ContentViewPagerAdapter; import com.project.realproject.fragments.SalaryCalculatorFragment; import com.project.realproject.fragments.SavingsCalculatorFragment; import static java.util.Calendar.getInstance; public class CalculatorActivity extends AppCompatActivity implements View.OnClickListener { private TabLayout tabLayout; private ViewPager viewPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_calculator); tabLayout = findViewById(R.id.tabLayout); viewPager = findViewById(R.id.viewPager); setupViewPager(viewPager); tabLayout.setupWithViewPager(viewPager); setupTabIcons(); } private void setupTabIcons() { View viewFirst = getLayoutInflater().inflate(R.layout.custom_tab, null); TextView txtFirst = viewFirst.findViewById(R.id.txt_tab); txtFirst.setText("월급계산기"); tabLayout.getTabAt(0).setCustomView(viewFirst); View viewSecond = getLayoutInflater().inflate(R.layout.custom_tab, null); TextView txtSecond = viewSecond.findViewById(R.id.txt_tab); txtSecond.setText("적금계산기"); tabLayout.getTabAt(1).setCustomView(viewSecond); } private void setupViewPager(ViewPager viewPager) { ContentViewPagerAdapter adapter = new ContentViewPagerAdapter(getSupportFragmentManager()); adapter.addFragment(SalaryCalculatorFragment.newInstance(), "First"); adapter.addFragment(SavingsCalculatorFragment.newInstance(), "Second"); viewPager.setAdapter(adapter); } @Override public void onClick(View view) { } }
true
3d8943ec75dc7b5a9e96114d91b971d43312c5cc
Java
LeandroBaroni/SVP_0.8.5
/src/View/Servicos/UpdServico.java
UTF-8
9,374
2.296875
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package View.Servicos; import Dao.Class.Funcionario; import Dao.Class.Servico; import Dao.Controller.FuncionarioControlador; import Dao.Controller.ServicoControlador; import java.sql.Date; import java.text.SimpleDateFormat; import javax.swing.JOptionPane; /** * * @author Nair Andrade */ public class UpdServico extends javax.swing.JDialog { Funcionario F = new Funcionario(); FuncionarioControlador FC = new FuncionarioControlador(); Servico S = new Servico(); ServicoControlador SC = new ServicoControlador(); public String usuario; public int codUsu; public int codServico; public int codPref; public String data; public String hora; /** * Creates new form UpdServico */ public UpdServico(java.awt.Frame parent, boolean modal) { super(parent, modal); initComponents(); } public void setUsuarios(){ F = FC.buscar(usuario); String tipo = F.getTipo(); System.out.println("USUARIO: " + F.getLogin() + "/ " + "Tipo: "+ tipo); } public void setValores(){ setUsuarios(); setBotao(); System.out.println("------------------------------"); } public void setBotao(){ txtServico.setText(Integer.toString(codServico)); txtPrefixo.setText(Integer.toString(codPref)); jDateChooser.setDate(Date.valueOf(data)); txtHora.setText(this.hora); txtPrefixo.setOpaque(true); txtPrefixo.setEditable(false); txtServico.setEditable(false); txtServico.setOpaque(true); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { btAlterar = new javax.swing.JButton(); btSair = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); txtServico = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); txtPrefixo = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); jDateChooser = new com.toedter.calendar.JDateChooser(); txtHora = new javax.swing.JFormattedTextField(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setPreferredSize(new java.awt.Dimension(383, 241)); btAlterar.setText("Alterar"); btAlterar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btAlterarActionPerformed(evt); } }); btSair.setText("Sair"); btSair.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btSairActionPerformed(evt); } }); jLabel1.setText("Cod. Serviço: "); jLabel2.setText("Prefixo: "); jLabel3.setText("Data/Horário: "); try { txtHora.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##:##"))); } catch (java.text.ParseException ex) { ex.printStackTrace(); } javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btAlterar) .addGap(18, 18, 18) .addComponent(btSair, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(41, 41, 41)) .addGroup(layout.createSequentialGroup() .addGap(23, 23, 23) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addComponent(jLabel1) .addComponent(jLabel3)) .addGap(55, 55, 55) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jDateChooser, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(txtHora, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(txtPrefixo, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtServico, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(20, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(47, 47, 47) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txtServico, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txtPrefixo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel3) .addComponent(jDateChooser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtHora, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 54, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btAlterar) .addComponent(btSair)) .addGap(21, 21, 21)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void btSairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSairActionPerformed GerenciarServicos form = new GerenciarServicos(null, true); form.usuario = F.getLogin(); form.setValores(); this.dispose(); form.setLocationRelativeTo(null); form.setVisible(true); }//GEN-LAST:event_btSairActionPerformed private void btAlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btAlterarActionPerformed SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd"); int pref = Integer.parseInt(txtPrefixo.getText()); int serv = Integer.parseInt(txtServico.getText()); String dat = sdf.format(jDateChooser.getDate()); System.out.println(dat); String hor = txtHora.getText() + ":00"; System.out.println("hor: " + hor); if(hor.length() != 8){ JOptionPane.showMessageDialog(null, "Hora de viagem Inválida", "Erro", JOptionPane.INFORMATION_MESSAGE); }else{ S = new Servico(serv, dat, hor, pref); SC.alterar(S); JOptionPane.showMessageDialog(null, "Serviço de viagem alterado com sucesso", "Erro", JOptionPane.OK_OPTION); GerenciarServicos form = new GerenciarServicos(null ,true); form.usuario = F.getLogin(); form.setValores(); this.dispose(); form.setLocationRelativeTo(null); form.setVisible(true); } }//GEN-LAST:event_btAlterarActionPerformed /** * @param args the command line arguments */ // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btAlterar; private javax.swing.JButton btSair; private com.toedter.calendar.JDateChooser jDateChooser; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JFormattedTextField txtHora; private javax.swing.JTextField txtPrefixo; private javax.swing.JTextField txtServico; // End of variables declaration//GEN-END:variables }
true
35d3cb7dae9716f6981cc0dcc114ecd2120d7905
Java
StevenMeiklejohn/Java_FruitMachine
/FruitMachine/app/src/main/java/example/codeclan/com/fruitmachine/Runner.java
UTF-8
694
2.65625
3
[]
no_license
package example.codeclan.com.fruitmachine; import java.util.ArrayList; /** * Created by user on 30/06/2017. */ public class Runner { Ui ui; Machine machine; User user; ArrayList<Reel> reels; public static void main(String[] args) { Ui ui = new Ui(); User user = new User("Steve", 100); Reel reel1 = new Reel(); Reel reel2 = new Reel(); Reel reel3 = new Reel(); ArrayList<Reel> reels = new ArrayList<Reel>(); reels.add(reel1); reels.add(reel2); reels.add(reel3); Machine machine = new Machine(10000, reels, 1000, ui, user); machine.insertCoin(); machine.play(); } }
true
c0c69985acfb78c1c56813a13f80a74150b21bc5
Java
lujx1994/oasys
/.svn/pristine/44/44ebf247c12e136e178ce482d1448a263724af8b.svn-base
UTF-8
1,466
2.203125
2
[]
no_license
package com.yanoda.rbac.domain; import java.util.List; public class User { private int id; private String username; private String password; private String truename; private int department_id; private String email; private int enabled; private int default_role_id; private List<Role> roleList; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getTruename() { return truename; } public void setTruename(String truename) { this.truename = truename; } public int getDepartment_id() { return department_id; } public void setDepartment_id(int department_id) { this.department_id = department_id; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public int getEnabled() { return enabled; } public void setEnabled(int enabled) { this.enabled = enabled; } public int getDefault_role_id() { return default_role_id; } public void setDefault_role_id(int default_role_id) { this.default_role_id = default_role_id; } public List<Role> getRoleList() { return roleList; } public void setRoleList(List<Role> roleList) { this.roleList = roleList; } }
true
b4781d87b591e435e4163280cff3ce0d2bb36541
Java
sbarbosa115/transport
/src/com/transport/classes/Vehicle.java
UTF-8
340
2.265625
2
[]
no_license
package com.transport.classes; public class Vehicle extends Agent { /* * This class represents the functionality of a particular vehicle crossings * between light, although we did not have time to implement * * * @see java.lang.Runnable#run() */ @Override public void run() { // TODO Auto-generated method stub } }
true
c0426bd4b73f40e9e7577236a6885976bfd86a29
Java
Rwuyao/ssm-login
/src/main/java/com/fs/model/page.java
UTF-8
940
2.5625
3
[]
no_license
package com.fs.model; public class page { private int num;//当前页 private int size=5;//一页多少条数据 private int start=0;//从都几条开始 private int sum;//一共有多少条 public int getNum() { return num; } public void setNum(int num) { this.num = num; } public int getSize() { return size; } public void setSize(int size) { this.size = size; } public int getStart() { return start; } public void setStart(int start) { this.start = start; } public int getSum() { return sum; } public void setSum(int sum) { this.sum = sum; } public page() { super(); // TODO Auto-generated constructor stub } public page(int num, int size, int start, int sum) { super(); this.num = num; this.size = size; this.start = start; this.sum = sum; } @Override public String toString() { return "page [num=" + num + ", size=" + size + ", start=" + start + ", sum=" + sum + "]"; } }
true
b1483f9cfb153fb8c1a0c1cdac4352e02dbe5e17
Java
pratannu/AirlineBooking
/src/main/java/airline/repositories/CityRepository.java
UTF-8
423
2.328125
2
[]
no_license
package airline.repositories; import airline.model.City; import org.springframework.stereotype.Service; import java.util.*; public class CityRepository { public List<City> getCities() { List<City> cities = new ArrayList<City>(); cities.add(new City("HYD", "Hyderabad")); cities.add(new City("BLR", "Bengaluru")); cities.add(new City("PUN", "Pune")); return cities; } }
true
1e5fa23d9ceede8a3acc2f9344bddf11171cc4cd
Java
bbossgroups/bboss
/bboss-websocket/src/org/frameworkset/web/socket/sockjs/SockJsMessageDeliveryException.java
UTF-8
877
2.484375
2
[ "Apache-2.0" ]
permissive
package org.frameworkset.web.socket.sockjs; import java.util.List; public class SockJsMessageDeliveryException extends SockJsException { private final List<String> undeliveredMessages; public SockJsMessageDeliveryException(String sessionId, List<String> undeliveredMessages, Throwable cause) { super("Failed to deliver message(s) " + undeliveredMessages + " for session " + sessionId, sessionId, cause); this.undeliveredMessages = undeliveredMessages; } public SockJsMessageDeliveryException(String sessionId, List<String> undeliveredMessages, String message) { super("Failed to deliver message(s) " + undeliveredMessages + " for session " + sessionId + ": " + message, sessionId, null); this.undeliveredMessages = undeliveredMessages; } public List<String> getUndeliveredMessages() { return this.undeliveredMessages; } }
true
5c3dcb6699ccbd21e881ffade3fd3d8b6b840a90
Java
csm/Jessie
/src/main/java/org/metastatic/jessie/provider/X500PrincipalList.java
UTF-8
7,526
2.078125
2
[]
no_license
/* X500PrincipalList.java -- A list of X.500 names. Copyright (C) 2006 Free Software Foundation, Inc. This file is a part of GNU Classpath. GNU Classpath is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GNU Classpath 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 General Public License for more details. You should have received a copy of the GNU General Public License along with GNU Classpath; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ package org.metastatic.jessie.provider; import java.io.PrintWriter; import java.io.StringWriter; import java.nio.ByteBuffer; import java.util.ConcurrentModificationException; import java.util.ListIterator; import java.util.NoSuchElementException; import javax.security.auth.x500.X500Principal; public final class X500PrincipalList implements Iterable<X500Principal> { private final ByteBuffer buffer; private int modCount; public X500PrincipalList (final ByteBuffer buffer) { this.buffer = buffer; modCount = 0; } public int size () { return (buffer.getShort (0) & 0xFFFF); } public int count () { int size = size (); int i = 0; for (int offset = 2; offset < size; i++) { int _size = (buffer.getShort (offset) & 0xFFFF); // We don't want this going into an infinite loop if // you mistakenly put a zero-length name. if (_size == 0) break; offset += _size + 2; } return i; } public X500Principal get (final int index) { if (index < 0) throw new IndexOutOfBoundsException ("negative index"); int size = size (); int i = 0; for (int offset = 2; offset < size; i++) { int _size = (buffer.getShort (offset) & 0xFFFF); if (_size == 0) throw new IndexOutOfBoundsException ("zero-length name encountered"); if (i == index) { byte[] buf = new byte[_size]; buffer.position (offset + 2); buffer.get (buf); return new X500Principal (buf); } offset += 2 + _size; } throw new IndexOutOfBoundsException ("limit: " + i + "; requested: " + index); } public void put (final int index, final X500Principal principal) { put (index, principal.getEncoded ()); } public void put (final int index, final byte[] encoded) { if (index < 0) throw new IndexOutOfBoundsException ("negative index"); int size = size (); int i = 0; for (int offset = 2; offset < size; i++) { int off = (buffer.getShort (offset) & 0xFFFF); if (i == index) { buffer.putShort (offset, (short) encoded.length); buffer.position (offset + 2); buffer.put (encoded); modCount++; return; } offset += 2 + off; } throw new IndexOutOfBoundsException ("limit: " + (i-1) + "; requested: " + index); } public void setSize (final int numNames, final int namesSize) { if (numNames < 1) throw new IllegalArgumentException ("must have at least one name"); int size = (numNames * 2) + namesSize; if (size < 3 || size > buffer.capacity () || size > 0xFFFF) throw new IllegalArgumentException ("size out of range; maximum: " + Math.min (buffer.capacity (), 0xFFFF)); buffer.putShort (0, (short) size); } public String toString () { return toString (null); } public String toString (final String prefix) { StringWriter str = new StringWriter (); PrintWriter out = new PrintWriter (str); if (prefix != null) out.print (prefix); out.print ("["); out.print (count ()); out.println ("] {"); for (Iterator it = new Iterator (); it.hasNext (); ) { if (prefix != null) out.print (prefix); out.print (" "); out.println (it.next ()); } if (prefix != null) out.print (prefix); out.print ("};"); return str.toString (); } public boolean equals (Object o) { if (!(o instanceof X500PrincipalList)) return false; X500PrincipalList that = (X500PrincipalList) o; if (size () != that.size ()) return false; for (Iterator it1 = new Iterator (), it2 = that.new Iterator (); it1.hasNext () && it2.hasNext (); ) { if (!it1.next ().equals (it2.next ())) return false; } return true; } public java.util.Iterator<X500Principal> iterator () { return new Iterator(); } public class Iterator implements ListIterator<X500Principal> { private final int modCount; private int index; private final int count; public Iterator () { this.modCount = X500PrincipalList.this.modCount; index = 0; count = count (); } public void add (X500Principal o) { throw new UnsupportedOperationException (); } public boolean hasNext () { return (index < count); } public boolean hasPrevious () { return (index > 0); } public X500Principal next () throws NoSuchElementException { if (modCount != X500PrincipalList.this.modCount) throw new ConcurrentModificationException (); try { return get (index++); } catch (IndexOutOfBoundsException ioobe) { throw new NoSuchElementException (); } } public int nextIndex () { if (hasNext ()) return (index + 1); return -1; } public X500Principal previous () throws NoSuchElementException { if (index == 0) throw new NoSuchElementException (); if (modCount != X500PrincipalList.this.modCount) throw new ConcurrentModificationException (); try { return get (--index); } catch (IndexOutOfBoundsException ioobe) { throw new NoSuchElementException (); } } public int previousIndex () { return (index - 1); } public void remove () { throw new UnsupportedOperationException (); } public void set (final X500Principal o) { throw new UnsupportedOperationException (); } } }
true
3f1a19a8782c3b75ee82dee42f39ecc648408203
Java
jeo/jeo
/contrib/geotools/src/test/java/io/jeo/geotools/GTTest.java
UTF-8
4,743
2.171875
2
[ "Apache-2.0" ]
permissive
/* Copyright 2013 The jeo project. All rights reserved. * * 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.jeo.geotools; import static org.junit.Assert.*; import java.util.Map; import io.jeo.vector.MapFeature; import org.geotools.feature.simple.SimpleFeatureBuilder; import org.geotools.feature.simple.SimpleFeatureTypeBuilder; import org.geotools.geometry.jts.GeometryBuilder; import io.jeo.vector.Feature; import io.jeo.vector.Schema; import io.jeo.vector.SchemaBuilder; import io.jeo.proj.Proj; import io.jeo.util.Util; import org.junit.Test; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; import org.opengis.feature.type.GeometryDescriptor; import com.vividsolutions.jts.geom.Point; public class GTTest { @Test public void testToSchema() { Schema schema = GT.schema(buildFeatureType()); assertNotNull(schema); assertEquals("widgets", schema.name()); assertEquals(Proj.crs(4326).getName(), schema.crs().getName()); assertEquals(4, schema.fields().size()); assertNotNull(schema.field("geometry")); assertEquals(Point.class, schema.field("geometry").type()); assertNotNull(schema.field("name")); assertEquals(String.class, schema.field("name").type()); assertNotNull(schema.field("id")); assertEquals(Integer.class, schema.field("id").type()); assertNotNull(schema.field("price")); assertEquals(Double.class, schema.field("price").type()); } @Test public void testFromSchema() { Schema schema = new SchemaBuilder("widgets").field("geometry", Point.class) .field("name", String.class).field("id", Integer.class).field("price", Double.class) .schema(); SimpleFeatureType featureType = GT.featureType(schema); assertNotNull(featureType.getDescriptor("geometry")); assertTrue(featureType.getDescriptor("geometry") instanceof GeometryDescriptor); assertEquals(Point.class, featureType.getDescriptor("geometry").getType().getBinding()); assertNotNull(featureType.getDescriptor("name")); assertEquals(String.class, featureType.getDescriptor("name").getType().getBinding()); assertNotNull(featureType.getDescriptor("id")); assertEquals(Integer.class, featureType.getDescriptor("id").getType().getBinding()); assertNotNull(featureType.getDescriptor("price")); assertEquals(Double.class, featureType.getDescriptor("price").getType().getBinding()); assertNotNull(featureType.getGeometryDescriptor()); } @Test public void testToFeature() { SimpleFeatureBuilder b = new SimpleFeatureBuilder(buildFeatureType()); b.add(new GeometryBuilder().point(0,0)); b.add("bomb"); b.add(1); b.add(10.99); SimpleFeature sf = b.buildFeature(null); Feature f = GT.feature(sf); assertNotNull(f.get("geometry")); assertTrue(f.get("geometry") instanceof Point); assertEquals("bomb", f.get("name")); assertEquals(1, f.get("id")); assertEquals(10.99, f.get("price")); assertTrue(f.has("geometry")); assertTrue(f.has("price")); assertFalse(f.has("NOT THERE AT ALL")); } @Test public void testFromFeature() { Feature f = new MapFeature(null, (Map)Util.map("geometry", new GeometryBuilder().point(0,0), "id", 1, "name", "bomb", "price", 10.99)); SimpleFeature sf = GT.feature(f); assertNotNull(sf.getAttribute("geometry")); assertTrue(sf.getAttribute("geometry") instanceof Point); assertEquals("bomb", sf.getAttribute("name")); assertEquals(1, sf.getAttribute("id")); assertEquals(10.99, sf.getAttribute("price")); } SimpleFeatureType buildFeatureType() { SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder(); tb.setName("widgets"); tb.setSRS("EPSG:4326"); tb.add("geometry", Point.class); tb.add("name", String.class); tb.add("id", Integer.class); tb.add("price", Double.class); return tb.buildFeatureType(); } }
true
13c84d7c46f45b2826554bf7e99b019da8c0ca79
Java
diqiuxiaogege/-saas
/src/main/java/com/tuiba/saasadmininster/SaasadmininsterApplication.java
UTF-8
494
1.6875
2
[]
no_license
package com.tuiba.saasadmininster; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @MapperScan("com.tuiba.saasadmininster.*.mapper") @MapperScan("com.tuiba.saasadmininster.*.dao") public class SaasadmininsterApplication { public static void main(String[] args) { SpringApplication.run(SaasadmininsterApplication.class, args); } }
true
88092b9b32c5d83c1236d2e6fb23f60c2a4c7f5e
Java
mattyb5722/Space-Game
/src/MainBody.java
UTF-8
6,611
2.765625
3
[]
no_license
import java.awt.Canvas; import java.awt.Dimension; import java.awt.Graphics; import java.awt.image.BufferStrategy; import java.awt.image.BufferedImage; import java.io.IOException; import javax.swing.JFrame; public class MainBody extends Canvas { private static final long serialVersionUID = 1L; public static int WIDTH = 1229; public static int HEIGHT = 691; private final String title = "Space Game"; private String frameRate = "60 Ticks, FPS 60"; private int screenSize = 2; private int level = 1; private int difficulty = 1; private int highscore = 0; private int enemyKilled = 0; // Enemies killed this level private final int healthCounterMax = 5; // Max time to health pack drop private int ammoCounter = 0; // Current time to ammo pack drop private final int ammoCounterMax = 1000;// Max time to ammo pack drop private PHASE phase = PHASE.MENU; // Current phase private PHASE prev = PHASE.MENU; // Previous phase private static MainBody main = new MainBody(); private static JFrame frame; private BufferedImageLoader loader = new BufferedImageLoader(); private SoundManager sound = new SoundManager(); private Textures tex = new Textures(this, loader); private Controller c = new Controller(this, sound, tex); private Player p = new Player(this, tex, c); private Menu m = new Menu(this, loader, sound, p, tex); private BufferedImage image = new BufferedImage( WIDTH, HEIGHT, BufferedImage.TYPE_INT_BGR); private BufferedImage backGround; public enum PHASE{ MENU, GAME, GAME_OVER, SETTING }; public void changeScreenSize(int size) { // Small: 956 x 537 70% of 1366 x 768 // Standard: 1229 x 691 90% of 1366 x 768 // Large: 1503 x 845 110% of 1366 x 768 if (size != screenSize) { if (size == 1) { // Small Screen WIDTH = 956; HEIGHT = 537; }else if (size == 2) { // Standard Screen WIDTH = 1229; HEIGHT = 691; }else if (size == 3) { // Large Screen WIDTH = 1503; HEIGHT = 845; } // Change Window Size main.setPreferredSize(new Dimension(WIDTH, HEIGHT)); main.setMaximumSize(new Dimension(WIDTH, HEIGHT)); main.setMinimumSize(new Dimension(WIDTH, HEIGHT)); frame.pack(); // Change Images and Menu sizes and location tex.setTextures(size); c.setSize(); p.setSize(); m.setSize(); screenSize = size; } } private void init(){ // Initialize values requestFocus(); try { backGround = loader.loadImage("/BackGround.png"); // Background image } catch (IOException e) {e.printStackTrace();} sound.playContinuously("/Background.wav"); // Play music this.addMouseListener(new MouseInput(this, sound, m)); this.addKeyListener(new KeyInput(p)); } public void startRound() { p.startRound(difficulty); // Set Player values and location c.createEnemy(1); prev = PHASE.MENU; phase = PHASE.GAME; } private void tick() { // Update Function if(phase == PHASE.GAME){ p.tick(); // Update Player c.tick(); // Update other objects ammoCounter += 1; if (ammoCounter >= ammoCounterMax) { // Spawn Ammo Pack ammoCounter -= ammoCounterMax; c.createAmmoPack(); } if (enemyKilled == (2*level)-1){ // End of Round level += 1; enemyKilled = 0; c.createEnemy((2*level)-1); if (level % healthCounterMax == 0) { // Spawn Health Pack c.createHealthPack(); } } } } private void render() { BufferStrategy bs = this.getBufferStrategy(); if(bs == null){ createBufferStrategy(3); // Triple buffering return; } Graphics g = bs.getDrawGraphics(); g.drawImage(image, 0, 0, getWidth(), getHeight(), this); g.drawImage(backGround, 0, 0, null); ////////////////////////////////// if(phase == PHASE.GAME){ p.render(g); // Render player c.render(g); // Render other objects } m.render(g); // Render interface and menu ////////////////////////////////// g.dispose(); bs.show(); } public void reset(){ // Reset Game prev = PHASE.MENU; phase = PHASE.MENU; if (level > highscore) { highscore = level; } c.reset(); // Delete Objects level = 1; enemyKilled = 0; ammoCounter = 0; } private void run() { init(); // Initialize values // Regulates number of ticks per second and frame rate long lastTime = System.nanoTime(); // Time of last check double ns = 1000000000 / 60.0; // Nanosecond double delta = 0; // Time from last tick int updates = 0; // Number of ticks int frames = 0; // Number of renders long timer = System.currentTimeMillis(); // Game Timer while(true){ // Game loop long now = System.nanoTime(); delta += (now - lastTime) / ns; // Update and/or render run time lastTime = now; if(delta >= 1){ // Sets cap of ticks per second tick(); // Update GameObjects updates++; delta--; } render(); // Render GameObjects and Menu frames++; if (System.currentTimeMillis() - timer > 1000){ // Per Second timer += 1000; frameRate = updates + " Ticks, FPS " + frames; updates = 0; frames = 0; } } } public static void main(String arg[]){ // Set Dimension of Window main.setPreferredSize(new Dimension(WIDTH, HEIGHT)); main.setMaximumSize(new Dimension(WIDTH, HEIGHT)); main.setMinimumSize(new Dimension(WIDTH, HEIGHT)); // Create Window frame = new JFrame(main.title); frame.add(main); frame.pack(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setResizable(false); frame.setLocationRelativeTo(null); frame.setVisible(true); main.run(); // Start Game loop } public PHASE getPhase() { return phase; } public String getFrameRate() { return frameRate; } public void setPhase(PHASE phase) { this.phase = phase; } public PHASE getPrev() { return prev; } public void setPrev(PHASE prev) { this.prev = prev; } public int getEnemyKilled() { return enemyKilled; } public void setEnemyKilled(int enemyKilled) { this.enemyKilled = enemyKilled; } public int getAmmoCounter() { return ammoCounter; } public void setAmmoCounter(int ammoCounter) { this.ammoCounter = ammoCounter; } public int getAmmoCounterMax() { return ammoCounterMax; } public int getHealthCounterMax() { return healthCounterMax; } public void setDifficulty(int difficulty) { this.difficulty = difficulty; } public int getDifficulty() { return difficulty; } public int getScreenSize() { return screenSize; } public int getLevel() { return level; } public int getHighscore() { return highscore; } }
true
f3b7fd6e8d6922e8392677785f9de0a32947ee14
Java
JL-shungen/CloudNote
/src/main/test/NotebookTest.java
UTF-8
1,934
2.234375
2
[]
no_license
import dao.NotebookDao; import entity.Notebook; import org.junit.Before; import org.junit.Test; import java.sql.Timestamp; import java.util.List; import java.util.Map; import java.util.UUID; public class NotebookTest extends BaseTest { @Test public void testFindNotebooksByUserId(){ String userId="52f9b276-38ee-447f-a3aa-0d54e7a736e4"; NotebookDao dao=ctx.getBean("noteBookDao", NotebookDao.class); List<Map<String, Object>> list=dao.findNotebooksByUserId(userId); for(Map map:list){ System.out.println(map); } } @Test public void testFindNotebookByNotebookId(){ String notebookId="5612df0f-2b3a-4a8c-8df7-e1de67b6abcd"; NotebookDao dao=ctx.getBean("notebookDao",NotebookDao.class); Notebook notebook=dao.findNotebookByNotebookId(notebookId); System.out.println(notebook); } //pass @Test public void testAddNotebook(){ Notebook notebook=new Notebook(); notebook.setId(UUID.randomUUID().toString()); notebook.setUserId("c0217351-7c9b-43b1-a407-7fe1fd228532"); notebook.setName("测试添加笔记本功能"); Timestamp time1 = new Timestamp(System.currentTimeMillis()); notebook.setCreateTime(time1); NotebookDao dao=ctx.getBean("notebookDao",NotebookDao.class); dao.addNotebook(notebook); } @Test public void testDeleteNotebook(){ String notebookId="69626d0d-82a2-4376-8972-c7bcf79b080d"; NotebookDao dao=ctx.getBean("notebookDao",NotebookDao.class); dao.deleteNotebook(notebookId); } @Test public void testUpdateNotebook(){ Notebook notebook=new Notebook(); notebook.setId("4e701af0-ae78-49c2-baa6-407904cdd69e"); notebook.setName("软件工程改名"); NotebookDao dao=ctx.getBean("notebookDao",NotebookDao.class); dao.updateNotebook(notebook); } }
true
e4ba4103724efade67a100a1c46d40b456783f94
Java
Shalaaaka/Assignments
/CoreJava8/Streams Assignment/Assignment5Q3/Assignment5Q3.java
UTF-8
1,981
3.59375
4
[]
no_license
import java.util.*; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import static java.util.stream.Collectors.toList; class Trader { private String name; private String city; public String getName() { return name; } public String getCity() { return city; } public Trader(String name, String city) { super(); this.name = name; this.city = city; } @Override public String toString() { return "Trader [name=" + name + ", city=" + city + "]"; } } public class Assignment5Q3 { public static List<String> printUniqueCities (List <Trader> traders) { List<String> cities=new ArrayList<String>(); cities=traders.stream().map(Trader::getCity).distinct().collect(toList()); System.out.println(cities); return null; } public static List<String> tradersFromPuneSortByName(List<Trader> traders) { List<String> list=new ArrayList<String>(); list=traders.stream().sorted(Comparator.comparing(Trader::getCity)).map(Trader::getName).collect(toList()); System.out.println(list); return null; } public static String allTrader3Names(List<Trader> traders) { String names=traders.stream().map(Trader::getName).distinct().sorted().reduce("", (n1, n2) -> n1 + n2); System.out.println(names); return null; } public static ArrayList<Trader> areAnyTradersFromIndore(ArrayList<Trader> traders) { boolean IndoreBased=traders.stream().anyMatch(e->e.getCity().matches("Indore")); System.out.println(IndoreBased); return null; } public static void main(String[] args) { ArrayList<Trader> trader=new ArrayList<Trader>(); Trader t1=new Trader("Shalaka","Pune"); Trader t2=new Trader("Neha","Mumbai"); Trader t3=new Trader("Smita","Delhi"); Trader t4=new Trader("Sneha","Indore"); trader.add(t1); trader.add(t2); trader.add(t3); trader.add(t4); printUniqueCities(trader); tradersFromPuneSortByName(trader); allTrader3Names(trader); areAnyTradersFromIndore(trader); } }
true
8e8506a503722dc351afba41e792c088d82e4dc4
Java
tdallas/sia-tp2
/src/main/java/selections/ProbabilisticTournamentSelection.java
UTF-8
1,316
2.9375
3
[ "MIT" ]
permissive
package selections; import characters.Character; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Random; public class ProbabilisticTournamentSelection extends TournamentSelectionMethod { private final double threshold; public ProbabilisticTournamentSelection(double percentage, Random rand, double threshold) { super(percentage, rand, 2); this.threshold = threshold; } @Override public List<Character> select(final List<Character> population, final int k) { List<Character> selectedList = new ArrayList<>(); List<Character> populationNoRepeated = new ArrayList<>(new HashSet<>(population)); Character selected; double r; for (int i = 0; i < k; i++) { r = getRand().nextDouble(); if (r < threshold) { selected = getFittest(populationNoRepeated); } else { selected = getLeastFit(populationNoRepeated); } selectedList.add(selected); } return selectedList; } @Override public String toString() { return "PROBABILISTIC_TOURNAMENT" + ", Percentage: " + getPercentage() + ", Threshold Parameter: " + threshold; } }
true
9f6385f4822fe7bdcd02ef78674cc8ed9b1eab5a
Java
jtap60/com.estr
/src/com/estrongs/android/pop/view/aj.java
UTF-8
2,034
1.640625
2
[]
no_license
package com.estrongs.android.pop.view; import android.os.Handler; import com.estrongs.android.util.ap; import com.estrongs.fs.impl.usb.e; import com.estrongs.fs.impl.usb.g; import java.util.ArrayList; import java.util.Iterator; class aj implements Runnable { aj(FileExplorerActivity paramFileExplorerActivity) {} public void run() { Object localObject1 = null; int i = 0; g[] arrayOfg; boolean bool; Object localObject3; Object localObject2; for (;;) { try { if (e.c()) { arrayOfg = e.a(); i = 1; bool = e.e(); if ((i == 0) || (!bool) || (FileExplorerActivity.A(a))) { break label191; } localObject3 = ap.d(); ap.e(); ArrayList localArrayList = ap.d(); Iterator localIterator = localArrayList.iterator(); localObject2 = localObject3; localObject1 = localArrayList; if (!localIterator.hasNext()) { break; } localObject1 = (String)localIterator.next(); if (!((ArrayList)localObject3).contains(localObject1)) { continue; } ((ArrayList)localObject3).remove(localObject1); continue; return; } } catch (Exception localException) { localException.printStackTrace(); } arrayOfg = e.b(); } for (;;) { localObject3 = localObject2; if (localObject2 == null) { localObject3 = new ArrayList(); } localObject2 = localException; if (localException == null) { localObject2 = new ArrayList(); } if (a.i == null) { break; } a.i.post(new ak(this, arrayOfg, bool, (ArrayList)localObject3, (ArrayList)localObject2)); return; label191: localObject2 = null; } } } /* Location: * Qualified Name: com.estrongs.android.pop.view.aj * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
true
0ca6d2192ffd4f31db876450da486d3eae09cc34
Java
FilipOlofsson/OTP-Version-2
/src/CryptographyController.java
UTF-8
539
2.96875
3
[]
no_license
import java.io.File; import java.io.IOException; class CryptographyController { void Perform(Arguments arg, String Input, String Key, String Output) { try { if(arg == Arguments.Decrypt) { Crypto.Decrypt(new File(Input), new File(Key), new File(Output)); } else { Crypto.Encrypt(new File(Input), new File(Key), new File(Output)); } } catch (IOException e) { e.printStackTrace(); } } } enum Arguments { Encrypt, Decrypt; }
true
2c3b07f3bedf26760a0d6b519ad6590d6348266d
Java
ricardorlg/YellowPepperTechInterview
/src/main/java/com/example/ricardo/questions/ResultMessagesQuestions.java
UTF-8
199
1.71875
2
[]
no_license
package com.example.ricardo.questions; public class ResultMessagesQuestions { public static RegistrationQuestion registrationResultMessage(){ return new RegistrationQuestion(); } }
true
b8bbb1578fc3b858cd444e7a8631a0baf9ecccd2
Java
abatanx/WebSocketLuaClusterServer
/src/main/java/jp/cielist/apps/wslua/server/ClientManager.java
UTF-8
1,224
2.453125
2
[ "MIT" ]
permissive
/** * WebSocket-Lua-ClusterServer * Copyright (C) 2017 CIEL, K.K., Interfair laboratory * ALL RIGHTS RESERVED. * @license: MIT **/ package jp.cielist.apps.wslua.server; import org.eclipse.jetty.websocket.api.Session; import org.luaj.vm2.Globals; import org.luaj.vm2.LuaValue; import java.util.*; public class ClientManager { private Set<WebSockMain> clients = Collections.synchronizedSet(new HashSet<>()); private ClientManagerDelegate delegate; public ClientManager(ClientManagerDelegate delegate) { this.delegate = delegate; } public int size() { return clients.size(); } public void add(WebSockMain ws) { int before = clients.size(); clients.add(ws); delegate.onSessionJoin(ws); if( before != clients.size() ) delegate.onSessionChanged(); } public void remove(WebSockMain ws) { int before = clients.size(); clients.remove(ws); delegate.onSessionLeave(ws); if( before != clients.size() ) delegate.onSessionChanged(); } public WebSockMain[] getClients() { return clients.toArray(new WebSockMain[0]); } public WebSockMain getLuaBySession(Session session) { for(WebSockMain ws : getClients()) { if( ws.getSession() == session ) return ws; } return null; } }
true
86673149a11f27034ddec9115c6a96285097b3ac
Java
DivyaSivaprakash/automation-practise-base-and-pom
/src/main/java/com/automation/pom/Summerdresspage.java
UTF-8
512
2.078125
2
[]
no_license
package com.automation.pom; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; public class Summerdresspage { public WebDriver driver; @FindBy(xpath="(//a[@class='product_img_link'])[2]") private WebElement dress1; public Summerdresspage(WebDriver driver2) { this.driver=driver2; PageFactory.initElements(driver, this); } public WebElement getDress1() { return dress1; } }
true
135232e1e28f146efdfb7cd80791ed11f278087a
Java
mondhs/spantus
/externals/experiment/spnt-exp-segment/src/main/java/org/spantus/exp/segment/services/impl/ExperimentPGSQLDao.java
UTF-8
831
2.234375
2
[]
no_license
package org.spantus.exp.segment.services.impl; import java.sql.DriverManager; import java.sql.SQLException; import org.spantus.exception.ProcessingException; public class ExperimentPGSQLDao extends ExperimentHsqlDao{ @Override public void init(){ try { Class.forName("org.postgresql.Driver").newInstance(); String url = "jdbc:postgresql://localhost/spnt-exp"; connection = DriverManager.getConnection(url, "sa", "sa"); connection.setAutoCommit(true); } catch (InstantiationException e) { destroy(); throw new ProcessingException(e); } catch (IllegalAccessException e) { destroy(); throw new ProcessingException(e); } catch (ClassNotFoundException e) { destroy(); throw new ProcessingException(e); } catch (SQLException e) { destroy(); throw new ProcessingException(e); } } }
true
54e12223012d6d95bc7bf22771edc5c5820a5f8a
Java
artvovc/cvsi
/cvsi/cvsi-core/src/main/java/com/winify/cvsi/core/dto/ConversationDto.java
UTF-8
1,569
2.171875
2
[]
no_license
package com.winify.cvsi.core.dto; import com.winify.cvsi.core.dto.error.ServerResponseStatus; import com.winify.cvsi.db.model.Message; import java.io.Serializable; import java.util.HashSet; import java.util.Set; public class ConversationDto extends ServerResponseStatus implements Serializable { private Long id; private String receptorUsername; private String title; private Long notReadMessages; private Long createdDate; // private Set<Message> messages = new HashSet<>(); public ConversationDto() { notReadMessages = 0L; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getReceptorUsername() { return receptorUsername; } public void setReceptorUsername(String receptorUsername) { this.receptorUsername = receptorUsername; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Long getNotReadMessages() { return notReadMessages; } public void setNotReadMessages(Long notReadMessages) { this.notReadMessages = notReadMessages; } public Long getCreatedDate() { return createdDate; } public void setCreatedDate(Long createdDate) { this.createdDate = createdDate; } // public Set<Message> getMessages() { // return messages; // } // // public void setMessages(Set<Message> messages) { // this.messages = messages; // } }
true
9b1102110000728f3a4a7ab1806b5b532229183f
Java
tmazal/Lab-2
/Lab2PartialSolution/src/main/java/pokerBase/Hand.java
UTF-8
6,516
3.59375
4
[]
no_license
package pokerBase; import java.util.ArrayList; import java.util.Collections; public class Hand { // private ArrayList<Card> Kickers = new ArrayList<Card>(); TODO: implement kickers for all hands (future labs) private HandScore HS = new HandScore(); private ArrayList<Card> CardsInHand; public Hand () { // Makes a Hand Deck deck1 = new Deck(); ArrayList <Card> CardsInHand = new ArrayList<Card>(); for (int i = 0; i<5; i++) { // Draws five cards from the deck CardsInHand.add(deck1.Draw()); } Collections.sort(CardsInHand); // Sorts by descending rank } public void setCardsInHand(ArrayList<Card> cardsInHand) { CardsInHand = cardsInHand; } public HandScore getHandScore() { return HS; } public void EvalHand(){ // Evaluates given hand for possible hand types (two pair, full house, etc.) Card FirstCard = CardsInHand.get(0); // Indexes Array into separate Cards. Enums could be implemented here. Card SecondCard = CardsInHand.get(1); Card ThirdCard = CardsInHand.get(2); Card FourthCard = CardsInHand.get(3); Card FifthCard = CardsInHand.get(4); // First if loop checks for all possible flushes (all suits are the same) if (FirstCard.geteSuit().getiSuitNbr() == SecondCard.geteSuit().getiSuitNbr() && SecondCard.geteSuit().getiSuitNbr() == ThirdCard.geteSuit().getiSuitNbr() && ThirdCard.geteSuit().getiSuitNbr() == FourthCard.geteSuit().getiSuitNbr() && FourthCard.geteSuit().getiSuitNbr() == FifthCard.geteSuit().getiSuitNbr()) { if (FifthCard.geteRank().getiRankNbr() == 10) { HS.setHandStrength(100); // ROYAL FLUSH HS.setHiHand(0); HS.setLoHand(0); return; } else if (FirstCard.geteRank().getiRankNbr() - 1 == SecondCard.geteRank().getiRankNbr() && SecondCard.geteRank().getiRankNbr() - 1 == ThirdCard.geteRank().getiRankNbr() && ThirdCard.geteRank().getiRankNbr() - 1 == FourthCard.geteRank().getiRankNbr() && FourthCard.geteRank().getiRankNbr() - 1 == FifthCard.geteRank().getiRankNbr()){ HS.setHandStrength(90); // STRAIGHT FLUSH HS.setHiHand(FirstCard.geteRank().getiRankNbr()); HS.setLoHand(0); return; } else { HS.setHandStrength(60); // FLUSH HS.setHiHand(FirstCard.geteRank().getiRankNbr()); HS.setLoHand(0); return; } } else if (FirstCard.geteRank().getiRankNbr() == FourthCard.geteRank().getiRankNbr() || SecondCard.geteRank().getiRankNbr() == FifthCard.geteRank().getiRankNbr()){ HS.setHandStrength(80); // FOUR OF A KIND (1st and 4th card or 2nd and 5th card are the same) HS.setHiHand(SecondCard.geteRank().getiRankNbr()); HS.setLoHand(0); return; } else if ((FirstCard.geteRank().getiRankNbr() == ThirdCard.geteRank().getiRankNbr() && FourthCard.geteRank().getiRankNbr() == FifthCard.geteRank().getiRankNbr()) || (FirstCard.geteRank().getiRankNbr() == SecondCard.geteRank().getiRankNbr() && ThirdCard.geteRank().getiRankNbr() == FifthCard.geteRank().getiRankNbr())){ HS.setHandStrength(70); // FULL HOUSE (1st and 3rd card or 3rd and 5th card are the same) if (ThirdCard.geteRank().getiRankNbr() < SecondCard.geteRank().getiRankNbr()) { HS.setHiHand(SecondCard.geteRank().getiRankNbr()); HS.setLoHand(ThirdCard.geteRank().getiRankNbr()); } else { HS.setLoHand(FourthCard.geteRank().getiRankNbr()); HS.setHiHand(SecondCard.geteRank().getiRankNbr()); } return; } else if (FirstCard.geteRank().getiRankNbr() - 1 == SecondCard.geteRank().getiRankNbr() && SecondCard.geteRank().getiRankNbr() - 1 == ThirdCard.geteRank().getiRankNbr() && ThirdCard.geteRank().getiRankNbr() - 1 == FourthCard.geteRank().getiRankNbr() && FourthCard.geteRank().getiRankNbr() - 1 == FifthCard.geteRank().getiRankNbr()){ HS.setHandStrength(50); // STRAIGHT (card ranks descend by one) HS.setHiHand(FirstCard.geteRank().getiRankNbr()); HS.setLoHand(0); return; } else if ((FirstCard.geteRank().getiRankNbr() == SecondCard.geteRank().getiRankNbr() && SecondCard.geteRank().getiRankNbr() == ThirdCard.geteRank().getiRankNbr()) || (SecondCard.geteRank().getiRankNbr() == ThirdCard.geteRank().getiRankNbr() && ThirdCard.geteRank().getiRankNbr() == FourthCard.geteRank().getiRankNbr()) || (ThirdCard.geteRank().getiRankNbr() == FourthCard.geteRank().getiRankNbr() && FourthCard.geteRank().getiRankNbr() == FifthCard.geteRank().getiRankNbr())){ HS.setHandStrength(40); // THREE OF A KIND (checks 3 permutations) HS.setHiHand(ThirdCard.geteRank().getiRankNbr()); // Middle card will always be the one in the 3-of-a-kind HS.setLoHand(0); return; } else if ((FirstCard.geteRank().getiRankNbr() == SecondCard.geteRank().getiRankNbr() && FourthCard.geteRank().getiRankNbr() == FifthCard.geteRank().getiRankNbr()) || (FirstCard.geteRank().getiRankNbr() == SecondCard.geteRank().getiRankNbr() && ThirdCard.geteRank().getiRankNbr() == FourthCard.geteRank().getiRankNbr()) || (SecondCard.geteRank().getiRankNbr() == ThirdCard.geteRank().getiRankNbr() && FourthCard.geteRank().getiRankNbr() == FifthCard.geteRank().getiRankNbr())){ HS.setHandStrength(30); // 2 PAIRS (checks 3 permutations) HS.setHiHand(SecondCard.geteRank().getiRankNbr()); // 2nd card will always be within the higher pair HS.setLoHand(FourthCard.geteRank().getiRankNbr()); // conversely, 4th card will always be within the lower pair return; } else if (FirstCard.geteRank().getiRankNbr() == SecondCard.geteRank().getiRankNbr() || SecondCard.geteRank().getiRankNbr() == ThirdCard.geteRank().getiRankNbr() || ThirdCard.geteRank().getiRankNbr() == FourthCard.geteRank().getiRankNbr() || FourthCard.geteRank().getiRankNbr() == FifthCard.geteRank().getiRankNbr()){ HS.setHandStrength(20); // 1 PAIR (checks 4 permutations) HS.setLoHand(0); if (FirstCard.geteRank().getiRankNbr() == SecondCard.geteRank().getiRankNbr()){ HS.setHiHand(FirstCard.geteRank().getiRankNbr()); } else if (SecondCard.geteRank().getiRankNbr() == ThirdCard.geteRank().getiRankNbr()){ HS.setHiHand(SecondCard.geteRank().getiRankNbr()); } else if (ThirdCard.geteRank().getiRankNbr() == FourthCard.geteRank().getiRankNbr()){ HS.setHiHand(ThirdCard.geteRank().getiRankNbr()); } else { HS.setHiHand(FourthCard.geteRank().getiRankNbr()); } return; } else { HS.setHandStrength(10); // Nothing -> HIGH CARD HS.setHiHand(FifthCard.geteRank().getiRankNbr()); HS.setLoHand(0); return; } } }
true
c5e1f3dcac0bd12197a2e83aadaf8b3784182eb2
Java
wesenbergg/SuMa-k2020
/SuMa13-Visitor/src/pokemon/Pokemon.java
UTF-8
1,836
3.640625
4
[]
no_license
package pokemon; import visitor.PokemonVisitor; public class Pokemon { private LizardPokemonState state; private int level; private int points = 0; public int getPoints() { return points; } public void setPoints(int points) { this.points = points; } public Pokemon() { state = CharmanderState.getInstance(); level = 5; } public Pokemon(int level) { state = CharmanderState.getInstance(); this.level = level; while(checkEvolve()); } public void levelUp() { level++; System.out.println("Level up!\nYour " + state.getName() + " grew to level " + level + "!"); if(checkEvolve()) System.out.println("Your pokemon evolved to " + state.getName() + "!"); } public void printPokedexInfo() { System.out.println("Name: " + state.getName() + " lvl." + level + "\n" + "Demonstrate main attack: " + state.attack()); System.out.println("Info: " + state.pokedexInfo()); System.out.println("This pokemon has collected: " + points + " bonus points.\n"); } private boolean checkEvolve() { if(level > 15 && this.state.getName().contains("Charmander")) return changeState(CharmeleonState.getInstance()); if(level > 35 && this.state.getName().contains("Charmeleon")) return changeState(CharizardState.getInstance()); return false; } private boolean changeState(LizardPokemonState newState) { this.state = newState; return true; } public void acceptVisitor(PokemonVisitor visitor) { try { switch (state.getName()) { case "Charmander": visitor.visitCharmander(this); break; case "Charmeleon": visitor.visitCharmeleon(this); break; case "Charizard": visitor.visitCharizard(this); default: break; } } catch(Exception e) { System.out.println(e); } } }
true
8cb044869dbb6fc9581466a617270e0f5678ddae
Java
anton1y/JMP
/Aliaksei.Samoilik/03. CreationalPatterns/Task1-abstractFactory/src/main/java/jmp/creationalPatterns/abstractFactory/factory/AccessDAOFactory.java
UTF-8
368
2.3125
2
[]
no_license
package jmp.creationalpatterns.abstractfactory.factory; import jmp.creationalpatterns.abstractfactory.dao.AccessPersonDAO; import jmp.creationalpatterns.abstractfactory.dao.PersonDAO; public class AccessDAOFactory extends AbstractDAOFactory { @Override public PersonDAO getPersonDAO(String fileName) { return new AccessPersonDAO(fileName); } }
true
d0b16007aff29ae338642cca1f19a4c23241d389
Java
AnkitMohil/ankit123
/Shopping2/src/test/java/Test/Shopping2/TestReadExcel.java
UTF-8
1,271
2.640625
3
[]
no_license
package Test.Shopping2; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.testng.annotations.Test; public class TestReadExcel { @Test public static Object[][] testreadExcel(){ Object[][] obj = null; File file = new File("C:\\Users\\training_b4c.06.01\\workspace\\Shopping2\\Resources\\Login.xlsx"); try { InputStream is= new FileInputStream(file); XSSFWorkbook workbook = new XSSFWorkbook(is); XSSFSheet sheet1= workbook.getSheet("Sheet1"); obj = new Object[sheet1.getLastRowNum()][]; for (int i=1; i<=sheet1.getLastRowNum(); i ++) { obj[i-1]=new Object[sheet1.getRow(i).getPhysicalNumberOfCells()]; for (int j=0 ; j<sheet1.getRow(i).getPhysicalNumberOfCells();j++) { obj[i-1][j]=sheet1.getRow(i).getCell(j).getStringCellValue(); } System.out.println(); } workbook.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return obj; } }
true
2a64c52e953cfd69c7c5bd6adfe659111e36b46f
Java
piomin/sample-spring-webflux
/src/main/java/pl/piomin/services/model/Person.java
UTF-8
248
1.96875
2
[]
no_license
package pl.piomin.services.model; import lombok.*; @Getter @Setter @NoArgsConstructor @AllArgsConstructor @ToString public class Person { private Integer id; private String firstName; private String lastName; private int age; }
true
ae49eacc8896ee4a22057f2bfcd4933d69bf2a73
Java
yb-youness/ng_Spring_BugTracker
/src/main/java/com/bugT/services/BugServicesImpl.java
UTF-8
786
2.28125
2
[]
no_license
package com.bugT.services; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.bugT.models.BugModel; import com.bugT.repos.BugRepo; @Service public class BugServicesImpl implements BugService { @Autowired private BugRepo _bugRepo; @Override public List<BugModel> getAllBugs() { return _bugRepo.findAll(); } @Override public BugModel getOneBug(int id) { return _bugRepo.findById(id).get(); } @Override public BugModel insertBug(BugModel bug) { return _bugRepo.save(bug); } @Override public void updateBug(int id, BugModel u_Bug) { u_Bug.setId(id); _bugRepo.save(u_Bug); } @Override public void deleteBug(int id) { _bugRepo.deleteById(id); } }
true
b615c01a6fd298bba272ff12bad42abf695453e2
Java
SethuSenthil/Data-Structures
/Spiraling/FileTemplate.java
UTF-8
2,638
3.203125
3
[ "Unlicense" ]
permissive
import java.io.*; public class FileTemplate { static String projectName = "Sprial"; public FileTemplate() { File fileName = new File("example.txt"); try { // read file BufferedReader input = new BufferedReader(new FileReader(fileName)); String text; // parse file while ((text = input.readLine()) != null) { // init vars System.out.println("SprialNum: " + text); int sprilNum = Integer.parseInt(text); String[][] grid = new String[sprilNum][sprilNum]; int sRow = 0; int sCol = sRow; int eRow = sprilNum - 1; int eCol = eRow; try { // calc loops for (int i = 0; i < grid.length; i++) for (int j = 0; j < grid[0].length; j++) grid[i][j] = "-"; while (sRow <= eRow && sCol <= eCol) { for (int col = sCol; col <= eCol; col++) grid[sRow][col] = "*"; sRow++; if (sCol > 0) sCol++; for (int row = sRow; row <= eRow; row++) grid[row][eCol] = "*"; eCol--; sRow++; for (int col = eCol; col >= sCol; col--) grid[eRow][col] = "*"; eRow--; eCol--; for (int row = eRow; row >= sRow; row--) grid[row][sCol] = "*"; sCol++; eRow--; } if (sprilNum % 4 == 2) grid[sprilNum / 2][(sprilNum / 2) - 1] = "-"; // print results for (int i = 0; i < grid.length; i++) { for (int j = 0; j < grid[0].length; j++) System.out.print(grid[i][j] + " "); System.out.println(); } } catch (NumberFormatException err) { System.out.println(err); } } } catch (IOException e) { System.out.println("File Not Found"); } } public static void main(String[] args) { System.out.println("Running " + projectName + " entry point..."); FileTemplate app = new FileTemplate(); } }
true
d83c9194cc120a940ee19c6763ad3dcb9efc70c6
Java
flymin/oo-buaa
/oo_course_e_2019_16071064_homework_9/src/MyPath.java
UTF-8
2,529
3.234375
3
[]
no_license
import com.oocourse.specs1.models.Path; import java.util.ArrayList; import java.util.Iterator; /** * 应用模块名称<p> * 代码描述<p> * Copyright: Copyright (C) 2019 XXX, Inc. All rights reserved. <p> * Company: XXX科技有限公司<p> * * @author gaoruiyuan * @since 2019/4/30 16:42 */ public class MyPath implements Path { private ArrayList<Integer> nodes; public MyPath(int... nodeList) { this.nodes = new ArrayList<>(); for (int node : nodeList) { this.nodes.add(node); } } @Override public int size() { return this.nodes.size(); } @Override public int getNode(int index) { return this.nodes.get(index); } @Override public boolean containsNode(int node) { for (int i = 0; i < this.nodes.size(); i++) { if (this.nodes.get(i) == node) { return true; } } return false; } public ArrayList<Integer> getDistinctNodes() { ArrayList<Integer> result = new ArrayList<>(); for (int node : this.nodes) { if (!result.contains(node)) { result.add(node); } } return result; } @Override public int getDistinctNodeCount() { ArrayList<Integer> distinctNode = this.getDistinctNodes(); return distinctNode.size(); } @Override public boolean equals(Object obj) { if (obj == null || !(obj instanceof Path)) { return false; } Path another = (Path)obj; if (another.size() != this.size()) { return false; } for (int index = 0; index < this.size(); index++) { if (this.getNode(index) != another.getNode(index)) { return false; } } return true; } @Override public boolean isValid() { return this.nodes.size() >= 2; } @Override public Iterator<Integer> iterator() { return this.nodes.iterator(); } @Override public int compareTo(Path another) { for (int index = 0; index < this.size(); index++) { if (this.getNode(index) < another.getNode(index)) { return -1; } else if (this.getNode(index) > another.getNode(index)) { return 1; } } if (this.size() < another.size()) { return -1; } else if (this.size() > another.size()) { return 1; } return 0; } }
true
776b37e0a1803ae8a93f91aca3d5af2adf8b6877
Java
Application-DataLake/StartupApp
/Service/StartupApp-1/src/main/java/com/app/user/vo/UserRequestVO.java
UTF-8
453
1.726563
2
[]
no_license
package com.app.user.vo; import java.io.Serializable; import com.app.user.entity.UserInfo; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; @Getter @Setter @ToString @AllArgsConstructor @NoArgsConstructor public class UserRequestVO implements Serializable{ /** * */ private static final long serialVersionUID = -8546770227433062085L; UserInfo user; }
true
d98467da14d471b0434af259ae00c0589686a81e
Java
RaviVaranasi/mocktesting
/src/main/java/com/availity/learning/mocktesting/UserRepository.java
UTF-8
1,312
2.421875
2
[]
no_license
package com.availity.learning.mocktesting; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import java.util.List; /** */ public class UserRepository extends HibernateDaoSupport implements UserDao { @SuppressWarnings("unchecked") public User getUser(Long id) { List<User> users = getHibernateTemplate().find("from User u where id=?", id); return users != null && !users.isEmpty() ? users.get(0) : new User(); } @SuppressWarnings("unchecked") public User getUser(String username) { List<User> users = getHibernateTemplate().find("from User u where username=?", username); return users != null && !users.isEmpty() ? users.get(0) : new User(); } public List<User> getUserByLastName(String lastname) { return null; //To change body of implemented methods use File | Settings | File Templates. } @SuppressWarnings("unchecked") public List<User> getUsers() { return getHibernateTemplate().find("from User u order by upper(u.username)"); } public User saveUser(User user) { getHibernateTemplate().saveOrUpdate(user); getHibernateTemplate().flush(); return user; } public void remove(Long id) { getHibernateTemplate().delete(this.getUser(id)); } public boolean isRegistered(String user) { return false; } }
true
ed7a196e54f35fcd9c71f3ae4b798523dabc42ab
Java
FrozenFreeFall/Android-tv-widget
/Demo/androidtvwidget/src/main/java/com/open/androidtvwidget/menu/OpenMenuItemView.java
UTF-8
4,424
2.109375
2
[ "Apache-2.0" ]
permissive
package com.open.androidtvwidget.menu; import android.content.Context; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CompoundButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RadioButton; import android.widget.TextView; import com.open.androidtvwidget.R; import com.open.androidtvwidget.utils.GenerateViewId; import com.open.androidtvwidget.utils.OPENLOG; /** * Created by hailongqiu on 2016/8/23. */ public class OpenMenuItemView extends LinearLayout implements OpenMenuItem.ItemView { private OpenMenuItem mItemData; private Context mContext; private ImageView mIconView; private CompoundButton mCompoundButton; private TextView mTitleView; private LayoutInflater mInflater; public OpenMenuItemView(Context context) { this(context, null, 0); } public OpenMenuItemView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public OpenMenuItemView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); this.mContext = context; // setFocusableInTouchMode(true); setFocusable(true); } @Override protected void onFinishInflate() { super.onFinishInflate(); mTitleView = (TextView) findViewById(R.id.title_tv); } @Override public void initialize(OpenMenuItem itemData) { this.mItemData = itemData; // setTitle(itemData.getTitle()); setIcon(itemData.getIconRes()); setTextSize(itemData.getTextSize()); setChecked(itemData, itemData.isChecked()); // 如果没有设置菜单ITEM ID,则默认设置ID. if (itemData.getId() == 0) { int id = GenerateViewId.getSingleton().generateViewId(); itemData.setId(id); } setId(itemData.getId()); // item ID. } public void setTitle(CharSequence title) { if (title != null) { mTitleView.setText(title); if (mTitleView.getVisibility() != VISIBLE) mTitleView.setVisibility(VISIBLE); } else { if (mTitleView.getVisibility() != GONE) mTitleView.setVisibility(GONE); } } public void setIcon(int icon) { if (mIconView == null && icon <= 0) return; if (mIconView == null) { insertIconView(); } if (icon > 0) { Drawable d = getContext().getResources().getDrawable(icon); mIconView.setImageDrawable(d); if (mIconView.getVisibility() != VISIBLE) { mIconView.setVisibility(VISIBLE); } } else { mIconView.setVisibility(GONE); } } public void setChecked(OpenMenuItem itemData, boolean checked) { // if (itemData.getCheckedView() != null) { // if (mCompoundButton == null) { // insertCompoundButton(itemData); // } // mCompoundButton.setChecked(checked); // } } /** * 设置字体. */ public void setTextSize(int size) { if (size > 0) { mTitleView.setTextSize(size); } } private void insertIconView() { LayoutInflater inflater = getInflater(); mIconView = (ImageView) inflater.inflate(R.layout.list_menu_item_icon, this, false); addView(mIconView, 0); } /** * 插入勾选view. */ private void insertCompoundButton(OpenMenuItem itemData) { mCompoundButton = new RadioButton(mContext); addView(mCompoundButton, 0); } private LayoutInflater getInflater() { if (mInflater == null) { mInflater = LayoutInflater.from(getContext()); } return mInflater; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { if (mIconView != null) { ViewGroup.LayoutParams lp = getLayoutParams(); LayoutParams iconLp = (LayoutParams) mIconView.getLayoutParams(); if (lp.height > 0 && iconLp.width <= 0) { iconLp.width = lp.height; } } super.onMeasure(widthMeasureSpec, heightMeasureSpec); } }
true
a4d04243720ca1a8bd6bc07c3ffa8440df0a368a
Java
CaveMa/Storyboard
/app/src/main/java/com/example/neema/storyboard/ForgotPasswordActivity.java
UTF-8
2,797
2.265625
2
[]
no_license
package com.example.neema.storyboard; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.util.Patterns; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseAuthException; public class ForgotPasswordActivity extends AppCompatActivity { Button resetButton; EditText emailInput; private FirebaseAuth mFirebaseAuth = FirebaseAuth.getInstance(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.forgotpassword); resetButton = findViewById(R.id.resetPasswordButton); emailInput = findViewById(R.id.emailInput); } public void resetPressed(View v) { // Display an error next to the email if it is empty if (TextUtils.isEmpty(emailInput.getText())) { emailInput.setError(getString(R.string.email_required)); } else if (!Patterns.EMAIL_ADDRESS.matcher(emailInput.getText().toString()).matches()) { emailInput.setError(getString(R.string.email_not_valid)); } else { final String userEmail = emailInput.getText().toString().trim(); mFirebaseAuth.sendPasswordResetEmail(userEmail).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { Toast.makeText(getApplicationContext(), getString(R.string.email_sent), Toast.LENGTH_LONG).show(); } else { String errorCode = ((FirebaseAuthException) task.getException()).getErrorCode(); switch (errorCode) { case "ERROR_USER_NOT_FOUND": Toast.makeText(getApplicationContext(), getString(R.string.email_does_not_exist), Toast.LENGTH_LONG).show(); break; case "ERROR_USER_DISABLED": Toast.makeText(getApplicationContext(), getString(R.string.account_disabled), Toast.LENGTH_LONG).show(); break; default: Toast.makeText(getApplicationContext(), getString(R.string.error), Toast.LENGTH_LONG).show(); } } } }); } } }
true
682c809218c33f48ec848935f3797077d771e235
Java
Muhaiminur/Fish-E-commerce-Android
/app/src/main/java/com/gtechnologies/fishbangla/API_GET/GET_USER_PROFILE.java
UTF-8
3,635
2.0625
2
[]
no_license
package com.gtechnologies.fishbangla.API_GET; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class GET_USER_PROFILE { @SerializedName("createdAt") @Expose private String createdAt; @SerializedName("referCode") @Expose private String referCode; @SerializedName("contact") @Expose private String contact; @SerializedName("buyerReferCode") @Expose private String buyerReferCode; @SerializedName("name") @Expose private String name; @SerializedName("id") @Expose private Integer id; @SerializedName("referenceCode") @Expose private String referenceCode; @SerializedName("email") @Expose private String email; @SerializedName("picture") @Expose private String picture; @SerializedName("auctionExpire") @Expose private String auctionExpire; @SerializedName("status") @Expose private String status; @SerializedName("updatedAt") @Expose private String updatedAt; public String getCreatedAt() { return createdAt; } public void setCreatedAt(String createdAt) { this.createdAt = createdAt; } public String getReferCode() { return referCode; } public void setReferCode(String referCode) { this.referCode = referCode; } public String getContact() { return contact; } public void setContact(String contact) { this.contact = contact; } public String getBuyerReferCode() { return buyerReferCode; } public void setBuyerReferCode(String buyerReferCode) { this.buyerReferCode = buyerReferCode; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getReferenceCode() { return referenceCode; } public void setReferenceCode(String referenceCode) { this.referenceCode = referenceCode; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPicture() { return picture; } public void setPicture(String picture) { this.picture = picture; } public String getAuctionExpire() { return auctionExpire; } public void setAuctionExpire(String auctionExpire) { this.auctionExpire = auctionExpire; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getUpdatedAt() { return updatedAt; } public void setUpdatedAt(String updatedAt) { this.updatedAt = updatedAt; } @Override public String toString() { return "GET_USER_PROFILE{" + "createdAt='" + createdAt + '\'' + ", referCode='" + referCode + '\'' + ", contact='" + contact + '\'' + ", buyerReferCode='" + buyerReferCode + '\'' + ", name='" + name + '\'' + ", id=" + id + ", referenceCode='" + referenceCode + '\'' + ", email='" + email + '\'' + ", picture='" + picture + '\'' + ", auctionExpire='" + auctionExpire + '\'' + ", status='" + status + '\'' + ", updatedAt='" + updatedAt + '\'' + '}'; } }
true
7ac0ba0c0429d702ebf830d31e49e9b928d96324
Java
Hansol-Jeong/Spring-practice
/TeamProject2/src/main/java/com/hanwoo/service/BlogServiceImpl.java
UTF-8
861
2.0625
2
[]
no_license
package com.hanwoo.service; import java.util.List; import com.hanwoo.domain.Blog; import com.hanwoo.domain.Blog_User; import com.hanwoo.persistence.BlogRepository; public class BlogServiceImpl implements BlogService { private BlogRepository blogRepository; public void insertBlog(Blog blog) { blogRepository.save(blog); } public void deleteBlog(Blog blog) { blogRepository.deleteById(blog.getBlog_id()); } public void updateBlog(Blog blog) { Blog findBlog = blogRepository.findById(blog.getBlog_id()).get(); findBlog.setTitle(blog.getTitle()); findBlog.setTag(blog.getTag()); findBlog.setStatus(blog.getStatus()); blogRepository.save(findBlog); } public Blog getBlog(Blog blog) { return blogRepository.findById(blog.getBlog_id()).get(); } public List<Blog> getBlogList() { return (List<Blog>) blogRepository.findAll(); } }
true
3de26ede5c4eb72cf5be6caadd51418eca5f7d54
Java
RotaruG/FarmApp-2.0
/.svn/pristine/49/49dded858a8a1fbf46295b1baf40ce377658bc2b.svn-base
UTF-8
2,383
2.40625
2
[]
no_license
package farmApp.Entities; import java.sql.Timestamp; /** * * @author Ghetto */ public class Personal { private int id; private String nume; private String prenume; private String functia; private Boolean statut; private Timestamp dataAngajare; private Timestamp dataConcediere; public Personal() { } public Personal(String nume, String prenume, String functia, Boolean statut, Timestamp dataAngajare, Timestamp dataConcediere) { this.nume = nume; this.prenume = prenume; this.functia = functia; this.statut = statut; this.dataAngajare = dataAngajare; this.dataConcediere = dataConcediere; } public Personal(int id, String nume, String prenume, String functia, Boolean statut, Timestamp dataAngajare, Timestamp dataConcediere) { this.id = id; this.nume = nume; this.prenume = prenume; this.functia = functia; this.statut = statut; this.dataAngajare = dataAngajare; this.dataConcediere = dataConcediere; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getNume() { return nume; } public void setNume(String nume) { this.nume = nume; } public String getPrenume() { return prenume; } public void setPrenume(String prenume) { this.prenume = prenume; } public String getFunctia() { return functia; } public void setFunctia(String functia) { this.functia = functia; } public Boolean getStatut() { return statut; } public void setStatut(Boolean statut) { this.statut = statut; } public Timestamp getDataAngajare() { return dataAngajare; } public void setDataAngajare(Timestamp dataAngajare) { this.dataAngajare = dataAngajare; } public Timestamp getDataConcediere() { return dataConcediere; } public void setDataConcediere(Timestamp dataConcediere) { this.dataConcediere = dataConcediere; } @Override public String toString() { return "Personal{" + "id=" + id + ", nume=" + nume + ", prenume=" + prenume + ", functia=" + functia + ", statut=" + statut + ", dataAngajare=" + dataAngajare + ", dataConcediere=" + dataConcediere + '}'; } }
true
1ebfa3d3deb484e074de514a3f7f38e46b18dd70
Java
Louisfigo/AlgsGo
/src/net/louis/algs/sort/QuickSorter.java
UTF-8
2,328
3.078125
3
[]
no_license
package net.louis.algs.sort; import edu.princeton.cs.algs4.In; import edu.princeton.cs.algs4.StdRandom; public class QuickSorter<T> extends SorterTemplate<T>{ private static final int CUT_OFF = 10; private InsertionSorter<T> insertionSorter = new InsertionSorter<>(); @Override public void sort(T[] input) { StdRandom.shuffle(input); insertionSorter.setComparator(comparator); } private void sortLow(T[] input,int low,int hi) { if(hi<=low+CUT_OFF) { insertionSorter.sort(input,low,hi); return; } int partitionIdx = partition(input,low,hi); sortLow(input,low,partitionIdx-1); sortLow(input,partitionIdx+1,hi); } private void sort3Way(T[] input,int low,int hi) { if(hi<=low+CUT_OFF) { insertionSorter.sort(input,low,hi); return; } int lowPt = low, hiPt = hi+1; int Leq = low, hieq = hi+1; T v = input[low]; while (true) { while(less(input[++lowPt],v)) if(lowPt == hi) break; while(less(v,input[--hiPt])) if(hiPt == low) break; if(lowPt==hiPt && eq(input[lowPt],v)) exch(input,low,lowPt); if(lowPt>=hiPt) break; exch(input,lowPt,hiPt); if(eq(input[lowPt],v)) exch(input,++Leq,lowPt); if(eq(input[hiPt],v)) exch(input,--hieq,hiPt); } lowPt= hiPt + 1; for (int k = low; k <= Leq; k++) exch(input, k, hiPt--); for (int k = hi; k >= hieq; k--) exch(input, k, lowPt++); sort3Way(input, low, hiPt); sort3Way(input, lowPt, hi); } private boolean eq(T left, T right) { return comparator.compare(left,right) ==0; } private int partition(T[]input,int low,int hi) { int lowPt = low; int hiPt = hi+1; T pv = input[low]; while(true) { while(less(input[++lowPt],pv)) if(lowPt == hi) break; while(less(pv,input[--hiPt])) if(hiPt==low) break; if(lowPt>=hiPt) break; exch(input,lowPt,hiPt); } exch(input,low,hiPt); return hiPt; } }
true
95d641cb401421dc0aec1abfb2dad1cea0d95acb
Java
pkhandel92/grokking-oo-design
/hotel-management-system/src/main/java/com/mgmt/hotel/search/SearchResponse.java
UTF-8
464
1.929688
2
[]
no_license
package com.mgmt.hotel.search; import com.mgmt.hotel.search.criteria.SearchCriteriaResponse; public class SearchResponse<T extends SearchCriteriaResponse> { private long requestId; private T t; public T getT() { return t; } public void setT(T t) { this.t = t; } public long getRequestId() { return requestId; } public void setRequestId(long requestId) { this.requestId = requestId; } }
true
76f964a5ec43da7286aa7c36b920f45a51889ef5
Java
topcoder-platform/tc-java-components
/components/data_validation/src/java/tests/com/topcoder/util/datavalidator/CompareDirectionTestCases.java
UTF-8
1,215
2.578125
3
[]
no_license
/* * Copyright (C) 2007 TopCoder Inc., All Rights Reserved. */ package com.topcoder.util.datavalidator; import junit.framework.TestCase; /** * <p> * Test the functionality of class <code>CompareDirection</code>. * </p> * * @author telly12 * @version 1.1 */ public class CompareDirectionTestCases extends TestCase { /** * Test method for 'CompareDirection.toString()'. */ public void testToString() { assertEquals("Test method for 'CompareDirection.toString()' failed.", "equal to", CompareDirection.EQUAL.toString()); assertEquals("Test method for 'CompareDirection.toString()' failed.", "greater than", CompareDirection.GREATER.toString()); assertEquals("Test method for 'CompareDirection.toString()' failed.", "greater than or equal to", CompareDirection.GREATER_OR_EQUAL.toString()); assertEquals("Test method for 'CompareDirection.toString()' failed.", "less than", CompareDirection.LESS.toString()); assertEquals("Test method for 'CompareDirection.toString()' failed.", "less than or equal to", CompareDirection.LESS_OR_EQUAL.toString()); } }
true
0b79661b123de6701d224729b5b7d3400702248a
Java
favorer/trunk
/core/src/test/java/com/opensymphony/xwork2/interceptor/annotations/AnnotatedAction.java
UTF-8
650
1.859375
2
[]
no_license
/* * Copyright (c) 2002-2006 by OpenSymphony * All rights reserved. */ package com.opensymphony.xwork2.interceptor.annotations; import com.opensymphony.xwork2.Action; /** * @author Zsolt Szasz, zsolt at lorecraft dot com * @author Rainer Hermanns */ public class AnnotatedAction extends BaseAnnotatedAction { @Before(priority=5) public String before() { log = log + "before"; return null; } public String execute() { log = log + "-execute"; return Action.SUCCESS; } @BeforeResult public void beforeResult() throws Exception { log = log +"-beforeResult"; } @After(priority=5) public void after() { log = log + "-after"; } }
true
689e05826a6ae9d9d0a7ceb555c0625b89a6e320
Java
CCP101/Wangbo_2021
/code_save/2021-02-02/Person/PersonReflect.java
UTF-8
992
3.15625
3
[ "Apache-2.0" ]
permissive
package Person; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class PersonReflect { public static void main(String[] args) { try { Class<?> aClass = Class.forName("Person.Person"); Constructor<?> con1 = aClass.getConstructor(); Person p1 = (Person) con1.newInstance(); Field name = aClass.getDeclaredField("name"); name.setAccessible(true); name.set(p1,"李四"); System.out.println(p1.toString()); Method mod = aClass.getMethod("setAge", int.class); mod.invoke(p1,18); System.out.println(p1.toString()); } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InstantiationException | NoSuchFieldException | InvocationTargetException e) { e.printStackTrace(); } } }
true
4897ce194c9088eda7e90c4c3ce73d46df6f390b
Java
tzjavadmg/dubbo-samples
/dubbo-samples-triple/src/main/java/org/apache/dubbo/sample/tri/generic/GenericServer.java
UTF-8
453
2.03125
2
[ "Apache-2.0" ]
permissive
package org.apache.dubbo.sample.tri.generic; import org.apache.dubbo.sample.tri.pojo.TriPojoServer; import org.apache.dubbo.sample.tri.util.TriSampleConstants; import java.io.IOException; public class GenericServer { public static void main(String[] args) throws IOException { TriPojoServer server = new TriPojoServer(TriSampleConstants.SERVER_PORT); server.initialize(); server.start(); System.in.read(); } }
true
2b36e3e04ce000eedbc4527cee91c0619a8f4970
Java
zhongxingyu/Seer
/Diff-Raw-Data/21/21_8f759edd1f8c8b0464fbe9a5738452e2f3ceba5f/RegularObjectImpl/21_8f759edd1f8c8b0464fbe9a5738452e2f3ceba5f_RegularObjectImpl_s.java
UTF-8
6,833
1.875
2
[]
no_license
/******************************************************************************* * Copyright (c) 2007 Exadel, Inc. and Red Hat, Inc. * Distributed under license by Red Hat, Inc. All rights reserved. * This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Exadel, Inc. and Red Hat, Inc. - initial API and implementation ******************************************************************************/ package org.jboss.tools.common.model.impl; import java.text.MessageFormat; import java.util.*; import org.jboss.tools.common.model.*; import org.jboss.tools.common.meta.*; import org.jboss.tools.common.model.event.XModelTreeEvent; import org.jboss.tools.common.model.util.XModelObjectLoaderUtil; public class RegularObjectImpl extends XModelObjectImpl implements XOrderedObject { private static final long serialVersionUID = 7942041044569562286L; protected RegularChildren children = null; public RegularObjectImpl() {} protected RegularChildren createChildren() { return new RegularChildren(); } public boolean areChildrenOrdered() { return children != null && children.areChildrenOrdered(); } public String name() { return get(XModelObjectConstants.XML_ATTR_NAME); } protected void onSetEntity(String name) { super.onSetEntity(name); if(children == null) { children = createChildren(); } children.clear(); children.setComparator(createComparator()); } protected Comparator<XModelObject> createComparator() { return EntityComparator.getComparator(getModelEntity()); } public boolean hasChildren() { return !children.isEmpty(); } protected void loadChildren() {} public XModelObject[] getChildren() { loadChildren(); return children.getObjects(); } public XModelObject[] getLoadedChildren() { return children.getObjects(); } public boolean addChild_0(XModelObject o) { if(o == null) { return false; } String entity = o.getModelEntity().getName(); XChild c = getModelEntity().getChild(entity); if(c == null) return false; if(c.getMaxCount() < Integer.MAX_VALUE && children.getChildrenCount(entity) >= c.getMaxCount()) { return false; } ((XModelObjectImpl)o).setParent_0(this); boolean b = children.addObject(o); if(b) { if(o.getErrorState() == 2 || o.getErrorChildCount() > 0) { registerErrorChild(); } if(o.getErrorState() == 1 || o.getWarningChildCount() > 0) { registerWarningChild(); } } return b; } public void removeChild_0(XModelObject o) { if(children.removeObject(o)) { if(o.getErrorState() == 2 || o.getErrorChildCount() > 0) { unregisterErrorChild(); } if(o.getErrorState() == 1 || o.getWarningChildCount() > 0) { unregisterWarningChild(); } } } public void set(String name, String value) { String ov = super.get(name); String opp = getPathPart(); super.set(name, value); String npp = getPathPart(); XModelObject po = getParent(); if(po == null || !(po instanceof RegularObjectImpl) || (opp != null && opp.equals(npp))) return; RegularObjectImpl p = (RegularObjectImpl)po; XModelObject c = p.children.change(this, opp, npp); if(c != null) { if(getModelEntity().getAttribute(XModelObjectLoaderUtil.ATTR_ID_NAME) != null) { int k = 1; while(c != null) { super.set(XModelObjectLoaderUtil.ATTR_ID_NAME, "" + k); //$NON-NLS-1$ npp = getPathPart(); c = p.children.change(this, opp, npp); k++; } return; } else if(hasIdAttr()) { int k = 1; while(c != null) { super.set(XModelObjectImpl.DUPLICATE, "" + k); //$NON-NLS-1$ npp = getPathPart(); if(k == 1 && npp.indexOf(XModelObjectImpl.DUPLICATE) < 0) { elementExists(c, name, value); return; } c = p.children.change(this, opp, npp); k++; } } else { if(ov == null) properties.remove(name); else super.set(name, ov); elementExists(c, name, value); } } } public XModelObject getChildByPathPart(String pathpart) { loadChildren(); return children.getObject(pathpart); } // diagnostic protected void elementExists(XModelObject o, String name, String value) { if(getModel().getService() == null) return; String mes = MessageFormat.format( "Cannot set {0} = {1} for {2}\nbecause {3} exists in the {4}", getAttrNameByXMLName(name), value, title(this), title(o), title(getParent())); getModel().getService().showDialog("Error", mes, new String[]{"OK"}, null, 1); } private static String title(XModelObject o) { return o.getAttributeValue(XModelObjectConstants.ATTR_ELEMENT_TYPE) + " " + //$NON-NLS-1$ o.getModelEntity().getRenderer().getTitle(o); } private String getAttrNameByXMLName(String name) { if(getModelEntity().getAttribute(name) != null) return name; XAttribute[] as = getModelEntity().getAttributes(); for (int i = 0; i < as.length; i++) if(name.equals(as[i].getXMLName())) return as[i].getName(); return name; } // implementation of interface XOrderedObject for ordered subclasses public int getIndexOfChild(XModelObject o) { return children.getIndex(o); } public boolean move(int from, int to, boolean firechange) { boolean b = children.move(from, to); if(b) { fireStructureChanged(XModelTreeEvent.STRUCTURE_CHANGED, this); if(firechange) setModified(true); } return b; } //TODO implement registering/unregistering error children public void replaceChildren(XModelObject[] objects) { for (int i = 0; i < objects.length; i++) { ((XModelObjectImpl)objects[i]).setParent_0(this); } children.replaceChildren(objects); changeTimeStamp(); } }
true
5559811249ba87989c245a7acf449116b7285f91
Java
andersonchau/spring_boot_demo
/src/main/java/com/and/demo/webappall/swagger/controller/SwaggerUIController.java
UTF-8
1,297
1.953125
2
[]
no_license
package com.and.demo.webappall.swagger.controller; import com.and.demo.webappall.base.domain.Job; import com.and.demo.webappall.base.exception.AppResourceNotFoundException; import com.and.demo.webappall.base.object.AppAPIResponse; import com.and.demo.webappall.swagger.dto.RegistrationRequest; import com.and.demo.webappall.swagger.dto.RegistrationResponse; import io.swagger.v3.oas.annotations.tags.Tag; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import io.swagger.v3.oas.annotations.*; @RestController @RequestMapping("/swaggerAPI") public class SwaggerUIController { @PostMapping(value = "/swaggerTest1/{id}",produces = "application/json; charset=utf-8") @Tag(name = "Member", description = "Member account information") public RegistrationResponse swaggerTest(@PathVariable("id") int jobId, @RequestBody RegistrationRequest regRequest ) { // demo return new RegistrationResponse(); } @GetMapping(value = "/swaggerTest2",produces = "application/json; charset=utf-8") @Tag(name = "Registration", description = "Visitor registration") public RegistrationResponse doingNothing () { // demo return new RegistrationResponse(); } }
true
0a7b5d196498aea9f1c90aeda68b6ed9715c035e
Java
lhserafim/ManipulandoPastas
/src/application/Program.java
UTF-8
1,796
3.640625
4
[]
no_license
package application; import java.io.File; import java.io.IOException; import java.util.Scanner; public class Program { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.print("Digite o caminho da pasta: "); String strPath = sc.next(); // caminho recebendo o caminho da pasta File path = new File(strPath); System.out.println("getName: " + path.getName()); System.out.println("getParent: " + path.getParent()); System.out.println("getPath: " + path.getPath()); try { // carregar o vetor com todos os diretórios do caminho File[] folders = path.listFiles(File::isDirectory); // dentro da função temos o filtro //File[] folders = path.listFiles(); // sem filtro System.out.println("PASTAS"); for (File c : folders) { System.out.println(c); } } catch (NullPointerException e) { System.out.println(e.getMessage()); } catch (RuntimeException e) { e.printStackTrace(); } try { // carregar o vetor com todos os diretórios do caminho File[] files = path.listFiles(File::isFile); // dentro da função temos o filtro System.out.println("FILES"); for (File c : files) { System.out.println(c); } } catch (NullPointerException e) { System.out.println(e.getMessage()); } catch (RuntimeException e) { e.printStackTrace(); } // Criando um diretório boolean status = new File(strPath + "/teste").mkdir(); System.out.println(status); sc.close(); } }
true