text stringlengths 14 410k | label int32 0 9 |
|---|---|
@Override
public void mouseClicked(MouseEvent arg0) {
JButton button = (JButton) arg0.getSource();
if (button.getName().equalsIgnoreCase("back")){
KanjiMemo.showPanel(KanjiMemo.MAIN_SCENE);
} else if (button.getName().equalsIgnoreCase("undo")){
drawingPanel.undo();
} else if (button.getName().equalsIgnoreCase("clear")){
drawingPanel.clearCanvas();
} else if (button.getName().equalsIgnoreCase("check")){
ArrayList<KjStroke> answer = chosenWord.getSimplifiedStrokeList();
if (KjKanjiComparator.compareKanji(answer, drawingPanel.getSimplified())<KjKanjiComparator.MAXIMUM_DIFFERENCE){
correct = true;
checkIcon.setIcon(new ImageIcon("./images/correct_32.png"));
} else {
checkIcon.setIcon(new ImageIcon("./images/wrong_32.png"));
}
checkNumber.setText(""+KjKanjiComparator.compareKanji(answer, drawingPanel.getSimplified()));
} else if (button.getName().equalsIgnoreCase("next")){
chosenWord.increaseTotalAnswer();
if (correct){
chosenWord.increaseCorrectAnswer();
}
chooseRandomKanji();
} else if (button.getName().equalsIgnoreCase("answer")){
answerText.setText(chosenWord.getPresentString());
answerDrawing.setRawStroke(chosenWord.getRawStrokeList());
answerDrawing.setSimplified(chosenWord.getSimplifiedStrokeList());
answerDrawing.repaint();
}
} | 8 |
protected boolean existsOnServer( String urn ) throws IOException {
URL url = urlFor(urn);
if( induceHeadErrors ) throw new ServerError("Not a real error ha ha h", 599, null, "HEAD", url.toString());
HttpURLConnection urlCon = (HttpURLConnection)url.openConnection();
urlCon.setRequestMethod("HEAD");
urlCon.connect();
int status = urlCon.getResponseCode();
if( debug ) System.err.println("HEAD "+url+" -> "+status);
if( status == 200 ) {
return true;
} else if( status == 404 ) {
return false;
} else {
byte[] errorText = null;
try {
errorText = StreamUtil.slurp(urlCon.getErrorStream());
} catch( Exception e ) { }
throw new ServerError(
"HEAD received unexpected response code "+status+"; "+urlCon.getResponseMessage(),
status,
errorText,
urlCon.getRequestMethod(),
url.toString()
);
}
} | 5 |
private void selected(Object obj)
{
System.out.println("?");
System.out.println(obj);
System.out.println(selectedNo);
if (checkable) {
WidgetChooserButton button = (WidgetChooserButton)(layout.itemAt(selectedNo).widget());
if (obj != objects.get(selectedNo)) {
selectedNo = objects.indexOf(obj);
button.setChecked(false);
} else {
button.setChecked(true);
}
}
} | 2 |
@Test
public static void testInfoQuery() throws Exception
{
String jobName = "TestInfoJob-" + System.currentTimeMillis() + Math.random();
final String PSV = "ECONOMODE";
final String on = "ON";
final String off = "OFF";
final String target;
ArrayList<Command> commands = new ArrayList<Command>();
commands.add(new Comment(" Testing 1 2 3 "));
UnsolicitedStatus printerStatus = new UnsolicitedStatus(
new UnsolicitedDeviceType(UnsolicitedDeviceType.InputValue.ON));
printerStatus.addInputListener(new InputEventListener() {
public void inputEventOccurred(InputEvent event) {
if (event.getSource() instanceof UnsolicitedDeviceType) {
UnsolicitedDeviceType usd = (UnsolicitedDeviceType)event.getSource();
System.err.printf("Code: %s Online: %s Display: %s%n",
usd.getCode(), usd.getOnline(), usd.getDisplay());
}
}
});
commands.add(printerStatus);
Job j = new Job(jobName, "Troy's Test Job");
j.getPageUStatus().addInputListener(new InputEventListener()
{
public void inputEventOccurred(InputEvent event)
{
if (event.getSource() instanceof UnsolicitedPageType)
{
System.err.println("Printed page " + ((UnsolicitedPageType)event.getSource()).getPage());
}
}
});
j.getJobUStatus().addInputListener(new InputEventListener() {
public void inputEventOccurred(InputEvent event) {
if (event.getSource() instanceof UnsolicitedJobType) {
System.err.println(event.getSource().toString());
}
}
});
commands.add(j);
Info info = new Info(VariableCategory.VARIABLES);
info.addInputListener(new InputEventListener()
{
public void inputEventOccurred(InputEvent event)
{
if (event.getSource() instanceof Variable)
{
System.err.println("Variable changed/added: " + event.getSource());
}
if (event.getSource() instanceof Info)
{
System.err.println("Info object changed: " + event.getSource());
}
}
});
commands.add(info);
Info infoConfig = new Info(VariableCategory.CONFIG);
infoConfig.addInputListener(new InputEventListener() {
public void inputEventOccurred(InputEvent event) {
if (event.getSource() instanceof Variable) {
System.err.println("config variable " + event.getSource());
}
}
});
commands.add(infoConfig);
commands.add(new EndOfJob(jobName));
SocketClient sc = SocketClient.getSocket(printer);
String output = sc.invokePjlCommands(commands);
if (output.length() > 0)
{
System.err.println("OUTPUT: " + output);
}
// set the target to the opposite of what it already is.
target = info.getVariable(PSV).getValue().equals(on) ? off : on;
assert infoConfig.getVariable("MEMORY").getValue().matches("^\\d+$")
: "Didn't get a number for the config variable MEMORY";
Variable newVariable = info.getVariable(PSV).copy();
newVariable.setValue(target);
jobName = "TestInfoJob-" + System.currentTimeMillis() + Math.random();
Vector<Command> commands2 = new Vector<Command>();
Job j2 = new Job(jobName);
commands2.add(j2);
commands2.add(new Set(newVariable));
Inquire inquire = new Inquire(info.getVariable(PSV));
commands2.add(inquire);
commands2.add(new EndOfJob(jobName));
inquire.addInputListener(new InputEventListener()
{
public void inputEventOccurred(InputEvent event)
{
System.err.println("Changed: " + ((Inquire)event.getSource()).getVariable().toString());
}
});
sc = SocketClient.getSocket(printer);
output = sc.invokePjlCommands(commands2);
if (output.length() > 0)
{
System.err.println("OUTPUT: " + output);
}
// verify ptsize is a number
assert inquire.getVariable().getValue().matches("^(OFF|ON)$")
: PSV + " of " + info.getVariable(PSV).getValue() + " isn't expected";
// verify that the one set through the event == the target value
assert inquire.getVariable().getValue().equals(target)
: "event variable doesn't match the target variable";
} | 9 |
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Photo photo = (Photo) o;
if (src != null ? !src.equals(photo.src) : photo.src != null) return false;
return true;
} | 5 |
private boolean readBlock() throws IOException {
if (this.debug) {
System.err.println("ReadBlock: blkIdx = " + this.currBlkIdx);
}
if (this.inStream == null) {
throw new IOException("reading from an output buffer");
}
this.currRecIdx = 0;
int offset = 0;
int bytesNeeded = this.blockSize;
while (bytesNeeded > 0) {
long numBytes = this.inStream.read(this.blockBuffer, offset,
bytesNeeded);
//
// NOTE
// We have fit EOF, and the block is not full!
//
// This is a broken archive. It does not follow the standard
// blocking algorithm. However, because we are generous, and
// it requires little effort, we will simply ignore the error
// and continue as if the entire block were read. This does
// not appear to break anything upstream. We used to return
// false in this case.
//
// Thanks to 'Yohann.Roussel@alcatel.fr' for this fix.
//
if (numBytes == -1) {
if (offset == 0) {
// Ensure that we do not read gigabytes of zeros
// for a corrupt tar file.
// See http://issues.apache.org/bugzilla/show_bug.cgi?id=39924
return false;
}
// However, just leaving the unread portion of the buffer dirty does
// cause problems in some cases. This problem is described in
// http://issues.apache.org/bugzilla/show_bug.cgi?id=29877
//
// The solution is to fill the unused portion of the buffer with zeros.
Arrays.fill(blockBuffer, offset, offset + bytesNeeded, (byte) 0);
break;
}
offset += numBytes;
bytesNeeded -= numBytes;
if (numBytes != this.blockSize) {
if (this.debug) {
System.err.println("ReadBlock: INCOMPLETE READ "
+ numBytes + " of " + this.blockSize
+ " bytes read.");
}
}
}
this.currBlkIdx++;
return true;
} | 7 |
private int[] updateDateIndexAndFormat(String[] words) {
int indexDate1 = -1;
int indexDate2 = -1;
int toSkip = -1;
for (int i = 0; i < words.length; i++) {
if (i != toSkip) {
for (int j = 0; j < dateFormats.size(); j++) {
SimpleDateFormat dateForm = dateFormats.get(j);
try {
dateForm.setLenient(false);
dateForm.parse(words[i]);
if (indexDate1 == -1) {
indexDate1 = i;
} else {
indexDate2 = i;
}
} catch (ParseException e) {
}
}
int[] otherResults = checkForOtherFormats(words, indexDate1,
indexDate2, i);
if (otherResults[0] != -1) {
indexDate1 = otherResults[0];
if (otherResults[2] == 1) {
toSkip = i + 1;
}
} else if (otherResults[1] != -1) {
indexDate2 = otherResults[1];
if (otherResults[2] == 1) {
toSkip = i + 1;
}
}
}
}
int[] result = { indexDate1, indexDate2 };
return result;
} | 9 |
public void update() {
int xa = 0, ya = 0;
if (up) ya--;
if (down) ya++;
if (left) xa--;
if (right) xa++;
if (xa != 0 || ya != 0) move(xa,ya);
} | 6 |
@RequestMapping(value = {"search", "s"})
@ResponseBody
public Map search(
@RequestParam int page,
@RequestParam(value = "limit") int pageSize,
@RequestParam(required = false, defaultValue = "0") int specialtyId,
@RequestParam(required = false, defaultValue = "0") int collegeId,
@RequestParam(required = false) String gradeName
) {
Map<String, Object> map = new HashMap<>();
Map<String, Object> conditions = new HashMap<>();
if (!Strings.isNullOrEmpty(gradeName)) {
conditions.put("grade_name", gradeName);
}
if (specialtyId != 0) {
conditions.put("specialty_id", specialtyId);
}
if (collegeId != 0) {
conditions.put("college_id", collegeId);
}
List<Grade> list = gradeService.search(page, pageSize, conditions);
int total = gradeService.count(conditions);
map.put("success", true);
map.put("total", total);
map.put("list", list);
return map;
} | 3 |
public final void stopCutscene(Player player) {
if (player.getX() != endTile.getX() || player.getY() != endTile.getY()
|| player.getPlane() != endTile.getPlane())
player.setNextWorldTile(endTile);
if (hiddenMinimap())
player.getPackets().sendBlackOut(0); // unblack
player.getPackets().sendConfig(1241, 0);
player.getPackets().sendResetCamera();
player.setLargeSceneView(false);
player.unlock();
deleteCache();
if (currentMapData != null) {
CoresManager.slowExecutor.execute(new Runnable() {
@Override
public void run() {
try {
if (currentMapData != null)
RegionBuilder.destroyMap(currentMapData[0],
currentMapData[1], currentMapData[1],
currentMapData[2]);
} catch (Throwable e) {
Logger.handle(e);
}
}
});
}
} | 7 |
@Override
Move makeMove() {
Move m = null;
if (!_started) {
while (true) {
String s = getGame().getMove();
if (s.equals("p")) {
break;
} else {
m = Move.create(s);
if (getBoard().isLegal(m)) {
return m;
} else {
getBoard().display.update((Move) null);
}
}
}
}
ArrayList[] legalMoves = {new ArrayList<Move>(), new ArrayList<Move>(),
new ArrayList<Move>()};
Iterator<Move> i = getBoard().legalMoves();
while (i.hasNext()) {
Move legalMove = i.next();
legalMoves[1 - evaluate(legalMove, getBoard(), 3, side())].add(
legalMove);
}
for (ArrayList<Move> moves : legalMoves) {
if (moves.size() > 0) {
m = moves.get(getGame().getRandomSource()
.nextInt(moves.size()));
break;
}
}
if (m == null) {
return null;
}
System.out.println(side().toString() + "::" + m.toString());
return m;
} | 8 |
public Bank(int n, double initialBalance)
{
accounts = new double[n];
for (int i = 0; i < accounts.length; i++)
accounts[i] = initialBalance;
bankLock = new ReentrantLock();
sufficientFunds = bankLock.newCondition();
} | 1 |
private static void loadUnpackedItemExamines() {
Logger.log("MusicHints", "Packing music hints...");
try {
BufferedReader in = new BufferedReader(
new FileReader(UNPACKED_PATH));
DataOutputStream out = new DataOutputStream(new FileOutputStream(
PACKED_PATH));
while (true) {
String line = in.readLine();
if (line == null)
break;
if (line.startsWith("//"))
continue;
String[] splitedLine = line.split(" - ", 2);
if (splitedLine.length < 2)
throw new RuntimeException(
"Invalid list for music hints line: " + line);
int musicId = Integer.valueOf(splitedLine[0]);
if(splitedLine[1].length() > 255)
continue;
out.writeShort(musicId);
writeAlexString(out, splitedLine[1]);
musicHints.put(musicId, splitedLine[1]);
}
in.close();
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} | 7 |
private boolean smaller(Rectangular base, Rectangular upper) {
if (base.length > upper.length && base.width > upper.width) return true;
return false;
} | 2 |
public static void zigZagTraversal(TreeNode root) {
if (root == null)
return;
Stack<TreeNode> parents = new Stack<TreeNode>();
Stack<TreeNode> childs = new Stack<TreeNode>();
boolean forward = true;
parents.add(root);
while (!parents.empty()) {
TreeNode current = parents.peek();
parents.pop();
current.print();
if (forward) {
if (current.right != null)
childs.push(current.right);
if (current.left != null)
childs.push(current.left);
} else {
if (current.left != null)
childs.push(current.left);
if (current.right != null)
childs.push(current.right);
}
if (parents.empty()) {
forward = !forward;
//swap the stacks
Stack<TreeNode> temp = parents;
parents = childs;
childs = temp;
}
}//end of while
} | 8 |
private void sendContentToOutputDevice(Vector<JSONObject> contentToShow, String type){
//if care display is used
if(useXMPPConnection){
xmppConnection.sendContentToScreen(contentToShow, type);
}
//for debugging without care_screen or output on other devices such as robots
else{
Utils.printWithDate("Sent " + type + " to output device. json-representation: " + contentToShow.toString(), Utils.DEBUGLEVEL.DEBUG);
String imageURL = "";
//if type is "survey" you have to simulate the user's answer
if(type.equals("surveys")){
//user_mood: badMood || neutralMood || goodMood
ArrayList<String> possibleMoods = new ArrayList<String>();
possibleMoods.add("badMood");
possibleMoods.add("neutralMood");
possibleMoods.add("goodMood");
String currentMood = possibleMoods.get(random.nextInt(possibleMoods.size()));
contextInformation.put("userMood", currentMood);
if(useLocalInterface) GUI.setMood(currentMood);
Utils.printWithDate("Current user mood: " + currentMood, Utils.DEBUGLEVEL.GENERAL);
reactToCurrentContext(contextInformation);
}
else if(type.equals("recommendations")){
//get images of all chosen recommendations
Vector<String> imageNames = jsonParser.getImagesOfRecommendations(contentToShow.toString());
for(String imageName : imageNames){
//get image url
imageURL = "http://" + serverUri + "/care_prototype/sites/default/files/" + imageName;
Utils.printWithDate("image url = " + imageURL, Utils.DEBUGLEVEL.DEBUG);
}
if(useLocalInterface){
GUI.setImage(imageURL);
}
}
}
} | 6 |
public boolean equals(Object x) {
if (!(x instanceof Entry))
return (false);
T[] a = arr.get();
if (a == null)
return (false);
Entry<?> e = (Entry<?>) x;
Object[] ea = e.arr.get();
if (ea == null)
return (false);
if (ea.length != a.length)
return (false);
for (int i = 0; i < a.length; i++) {
if (a[i] != ea[i])
return (false);
}
return (true);
} | 8 |
public int trap(int[] A) {
int len = A.length;
int [] maxL = new int[len];
int [] maxR = new int[len];
int max = 0;
for(int i = 0; i < len; ++i){
maxL[i] = max;
if(max < A[i]) max = A[i];
}
max = 0;
for(int i = len - 1; i >= 0; --i){
maxR[i] = max;
if(max < A[i]) max = A[i];
}
int res = 0;
for(int i = 0; i < len; ++i){
int tmp = Math.min(maxL[i], maxR[i]);
res += A[i] < tmp ? tmp - A[i] : 0;
}
return res;
} | 6 |
public Utility(ModManager McLauncher) {
if(McLauncher!=null){
this.McLauncher = McLauncher;
gamePath = McLauncher.gamePath;
modPath = McLauncher.modPath;
con = McLauncher.con;
if(System.getProperty("os.name").toLowerCase().contains("windows")){
con.log("Log","OS Windows");
//OS="win";
}
else if(System.getProperty("os.name").toLowerCase().contains("linux")){
con.log("Log","OS Linux");
//OS="linux";
Font linuxfont = new Font("SansSerif", Font.PLAIN, 11);
McLauncher.tglbtnNewModsFirst.setFont(linuxfont);
McLauncher.tglbtnCloseAfterLaunch.setFont(linuxfont);
McLauncher.tglbtnCloseAfterUpdate.setFont(linuxfont);
McLauncher.tglbtnSendAnonData.setFont(linuxfont);
McLauncher.tglbtnDeleteBeforeUpdate.setFont(linuxfont);
McLauncher.tglbtnAlertOnModUpdateAvailable.setFont(linuxfont);
}
else if(System.getProperty("os.name").toLowerCase().contains("mac")){
con.log("Log","OS Mac");
//OS="mac";
}
}
} | 4 |
@Override
protected boolean xhas_in ()
{
// If we are in the middle of reading the messages, there are
// definitely more parts available.
if (more_in)
return true;
// We may already have a message pre-fetched.
if (prefetched)
return true;
// Try to read the next message.
// The message, if read, is kept in the pre-fetch buffer.
Pipe[] pipe = new Pipe[1];
prefetched_msg = fq.recvpipe (pipe);
// It's possible that we receive peer's identity. That happens
// after reconnection. The current implementation assumes that
// the peer always uses the same identity.
// TODO: handle the situation when the peer changes its identity.
while (prefetched_msg != null && prefetched_msg.is_identity ())
prefetched_msg = fq.recvpipe (pipe);
if (prefetched_msg == null)
return false;
assert (pipe[0] != null);
Blob identity = pipe[0].get_identity ();
prefetched_id = new Msg(identity.data());
prefetched_id.set_flags (Msg.more);
prefetched = true;
identity_sent = false;
return true;
} | 5 |
public static void main(String[] args) {
boolean b = test1(0) && test2(2) && test3(2);
System.out.println("expression is " + b);
} | 2 |
public IEntityImage createFile(String... dotStrings) throws IOException, InterruptedException {
dotStringFactory = new DotStringFactory(colorSequence, stringBounder, dotData);
shapeMap = new HashMap<IEntity, Shape>();
printGroups(null);
printEntities(getUnpackagedEntities());
// final Map<Link, Line> lineMap = new HashMap<Link, Line>();
for (Link link : dotData.getLinks()) {
final String shapeUid1 = getShapeUid(link.getEntity1());
final String shapeUid2 = getShapeUid(link.getEntity2());
String ltail = null;
if (shapeUid1.startsWith(Cluster.CENTER_ID)) {
ltail = getCluster(link.getEntity1().getParent()).getClusterId();
}
String lhead = null;
if (shapeUid2.startsWith(Cluster.CENTER_ID)) {
lhead = getCluster(link.getEntity2().getParent()).getClusterId();
}
final FontConfiguration labelFont = new FontConfiguration(dotData.getSkinParam().getFont(
FontParam.ACTIVITY_ARROW, null), HtmlColor.BLACK);
final Line line = new Line(shapeUid1, shapeUid2, link, colorSequence, ltail, lhead, dotData.getSkinParam(),
stringBounder, labelFont);
// lineMap.put(link, line);
dotStringFactory.addLine(line);
if (link.getEntity1().getType() == EntityType.NOTE && onlyOneLink(link.getEntity1())) {
final Shape shape = shapeMap.get(link.getEntity1());
((EntityImageNote) shape.getImage()).setOpaleLine(line, shape);
line.setOpale(true);
} else if (link.getEntity2().getType() == EntityType.NOTE && onlyOneLink(link.getEntity2())) {
final Shape shape = shapeMap.get(link.getEntity2());
((EntityImageNote) shape.getImage()).setOpaleLine(line, shape);
line.setOpale(true);
}
}
if (dotStringFactory.illegalDotExe()) {
return error(dotStringFactory.getDotExe());
}
final Dimension2D dim = Dimension2DDouble.delta(dotStringFactory.solve(dotStrings), 10);
final HtmlColor border;
if (dotData.getUmlDiagramType() == UmlDiagramType.STATE) {
border = getColor(ColorParam.stateBorder, null);
} else {
border = getColor(ColorParam.packageBorder, null);
}
final SvekResult result = new SvekResult(dim, dotData, dotStringFactory, border);
result.moveSvek(6, 0);
return result;
} | 9 |
public static boolean zipFolder(File folder, String fileName){
boolean success = false;
if(!folder.isDirectory()){
return false;
}
if(fileName == null){
fileName = folder.getAbsolutePath()+ZIP_EXT;
}
ZipArchiveOutputStream zipOutput = null;
try {
zipOutput = new ZipArchiveOutputStream(new File(fileName));
success = addFolderContentToZip(folder,zipOutput,"");
zipOutput.close();
} catch (IOException e) {
e.printStackTrace();
return false;
}
finally{
try {
if(zipOutput != null){
zipOutput.close();
}
} catch (IOException e) {}
}
return success;
} | 5 |
private final void method2872(int i, int i_90_) {
anInt8918++;
for (Class348_Sub43 class348_sub43
= ((Class348_Sub43)
((Class348_Sub16_Sub1) aClass348_Sub16_Sub1_8958)
.aClass262_8848.getFirst(i + -2005674596));
class348_sub43 != null;
class348_sub43
= ((Class348_Sub43)
((Class348_Sub16_Sub1) aClass348_Sub16_Sub1_8958)
.aClass262_8848.nextForward((byte) 68))) {
if (i_90_ < 0 || ((i_90_ ^ 0xffffffff)
== (((Class348_Sub43) class348_sub43).anInt7067
^ 0xffffffff))) {
if (((Class348_Sub43) class348_sub43).aClass348_Sub16_Sub5_7081
!= null) {
((Class348_Sub43) class348_sub43)
.aClass348_Sub16_Sub5_7081
.method2902(Class22.anInt339 / 100);
if (((Class348_Sub43) class348_sub43)
.aClass348_Sub16_Sub5_7081.method2895())
((Class348_Sub16_Sub1) aClass348_Sub16_Sub1_8958)
.aClass348_Sub16_Sub4_8855.method2883
(((Class348_Sub43) class348_sub43)
.aClass348_Sub16_Sub5_7081);
class348_sub43.method3299((byte) 72);
}
if ((((Class348_Sub43) class348_sub43).anInt7087 ^ 0xffffffff)
> -1)
aClass348_Sub43ArrayArray8928
[((Class348_Sub43) class348_sub43).anInt7067]
[((Class348_Sub43) class348_sub43).anInt7071]
= null;
class348_sub43.removeNode();
}
}
if (i != 2005674600)
anIntArray8902 = null;
} | 7 |
protected void addImpl(int index, int sublistIndex, int sublistOffset, T item) {
if (sublistIndex < headSublistIndex + (calculateSublistsUsed() >>> 1)) {
if (index == 0) {
addFirst(item);
} else {
CircularListInternal<T> prev = sublists.get(headSublistIndex);
if (sublistOffset == 0) {
sublistIndex -= 1;
sublistOffset = sublists.get(sublistIndex).size() - 1;
} else {
sublistOffset -= 1;
}
T carryItem = prev.removeHead();
CircularListInternal<T> next = prev;
for (int j = headSublistIndex + 1; j <= sublistIndex; j++) {
next = sublists.get(j);
prev.addTail(next.removeHead());
prev = next;
}
next.add(sublistOffset, item);
addFirst(carryItem);
}
} else {
if (index == size) {
add(item);
} else {
CircularListInternal<T> prev = sublists.get(tailSublistIndex);
T carryItem = prev.removeTail();
CircularListInternal<T> next = prev;
for (int j = tailSublistIndex - 1; j >= sublistIndex; j--) {
next = sublists.get(j);
prev.addHead(next.removeTail());
prev = next;
}
next.add(sublistOffset, item);
add(carryItem);
}
}
} | 6 |
public void render(){
for(int y = 0; y < map.length; y++){
for(int x = 0; x < map[0].length; x++){
int tile = map[x][y];
if(tile == Tile.GRASS)
screen.render(Tiles.GRASS, x * tileWidth, y * tileHeight);
else if(tile == Tile.WALL)
screen.render(Tiles.WALL, x * tileWidth, y * tileHeight);
}
}
screen.render(Tiles.HERO, hero.x / tileWidth, hero.y / tileHeight);
} | 4 |
public void save(){
if(this.getId() != null){
String q = "SELECT id, name " +
"FROM call_types " +
"WHERE id = ?";
try {
PreparedStatement statement = ru.vladambulance.call.Type.Type.getConnection().prepareStatement(q,
ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_UPDATABLE);
statement.setInt(1, this.getId());
ResultSet resultSet = statement.executeQuery();
if(resultSet.next()){
resultSet.updateString("name", this.getName());
resultSet.updateRow();
}
} catch (SQLException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
} else {
String q = "INSERT INTO call_types (name) " +
"VALUES (?)";
try {
PreparedStatement statement = ru.vladambulance.call.Type.Type.getConnection().prepareStatement(q,
Statement.RETURN_GENERATED_KEYS);
statement.setString(1, this.getName());
statement.executeUpdate();
ResultSet resultSet = statement.getGeneratedKeys();
if(resultSet.next()){
this.setId(resultSet.getInt(1));
}
} catch (SQLException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
} | 5 |
public Vector<BaseClass> getRankedClasses(int rank) {
Vector<BaseClass> bc = new Vector<>();
for (ClassMap item : _classMap) {
if (item.getRace().getName().equals(_race.getName())) {
if (item.getAverage() == rank) {
bc.add(item.getClassType());
}
}
}
return bc;
} | 3 |
static public int[] arraysDims(String[] arr) {
if (arr.length > 1) {
int[] idx = new int[arr.length - 1];
for (int i = 1; i < arr.length; i++) {
idx[i - 1] = Integer.parseInt(arr[i]);
}
return idx;
}
return null;
} | 2 |
private int evaluateValueofBoardForWhite(Board board) {
int wValue = 0;
if (board.isWhiteWinner()) {
wValue += POINT_WON;
return wValue;
} else {
wValue = WhiteBlackPiecesDifferencePoints(board);
// wValue += BoardPositionPoints(board);
wValue /= board.blackPieces;
}
return wValue;
} | 1 |
public ClassFile getClassFile2() {
ClassFile cfile = classfile;
if (cfile != null)
return cfile;
classPool.compress();
if (rawClassfile != null) {
try {
classfile = new ClassFile(new DataInputStream(
new ByteArrayInputStream(rawClassfile)));
rawClassfile = null;
getCount = GET_THRESHOLD;
return classfile;
}
catch (IOException e) {
throw new RuntimeException(e.toString(), e);
}
}
InputStream fin = null;
try {
fin = classPool.openClassfile(getName());
if (fin == null)
throw new NotFoundException(getName());
fin = new BufferedInputStream(fin);
ClassFile cf = new ClassFile(new DataInputStream(fin));
if (!cf.getName().equals(qualifiedName))
throw new RuntimeException("cannot find " + qualifiedName + ": "
+ cf.getName() + " found in "
+ qualifiedName.replace('.', '/') + ".class");
classfile = cf;
return cf;
}
catch (NotFoundException e) {
throw new RuntimeException(e.toString(), e);
}
catch (IOException e) {
throw new RuntimeException(e.toString(), e);
}
finally {
if (fin != null)
try {
fin.close();
}
catch (IOException e) {}
}
} | 9 |
public void migrateToUUID() {
// Bail if no-one has ever been warned
// or this is a first run
if (!getConfig().contains("Warned")) {
return;
}
// Get all the currently warned players and put them in a HashMap
Map<String,Object> userList = getConfig().getConfigurationSection("Warned").getValues(false);
Integer c = 0;
final List<String> players = new ArrayList<String>();
// Iterate the hashmap
for(Map.Entry<String,Object> entry : userList.entrySet()) {
String identifier = entry.getKey();
// Only do this if the current player isn't already migrated
if (!getConfig().contains("Warned." + identifier.toLowerCase()+".name")) {
players.add(identifier);
c++;
}
}
if (c > 0) {
this.logger.info("[BadWords] About to migrate " + c + " players to UUID support");
Bukkit.getScheduler().runTaskAsynchronously(this, new Runnable() {
@Override
public void run() {
UUIDFetcher fetcher = new UUIDFetcher(players, true);
Map<String, UUID> response = null;
Integer d = 0;
try {
response = fetcher.call();
for (Map.Entry<String, UUID> entry : response.entrySet()) {
Integer warn = getConfig().getInt("Warned."+entry.getKey().toLowerCase()+".remaining");
Long timestamp = getConfig().getLong("Warned."+entry.getKey().toLowerCase()+".timestamp");
// Add a new entry with the UUID as the key
addUUIDEntry(entry.getValue(), warn, timestamp, entry.getKey().toLowerCase());
// Remove the old entry
delPreUUIDEntry(entry.getKey().toLowerCase());
//logger.info("[BadWords] Migrated user:" + entry.getKey() + " UUID:" + entry.getValue());
d++;
}
} catch (Exception e) {
logger.warning("[BadWords] Unable to contact Mojang UUID lookup - aborting migration");
}
logger.info("[BadWords] Migrated " + d + " players to UUID support");
}
});
}
} | 6 |
public boolean isValidPassword(String userName, String password) {
try {
String pwdFromDB = loginDao.getUserPassword(userName);
if (null != pwdFromDB) {
if (pwdFromDB.equals(password)) {
return true;
}
}
} catch (Exception ex) {
if (!(ex instanceof DaoException)) {
ex.printStackTrace();
}
throw new ServiceException("global.exception.message");
}
return false;
} | 4 |
public void setReachable() {
if (!reachable) {
reachable = true;
setSingleReachable();
}
} | 1 |
private void number() {
// Some preliminaries
int tempCharPos = charPos;
int x = nextChar;
tempString = "";
//tempString += (char)x;
// So if we are here, we have a number so, crunch numbers until a . or non number
while((x>= 48)&&(x <=57)){ // while x is an element of the set {0,1,2,3,4,5,6,7,8,9}
// eat the nextNumber
tempString += (char)x;
nextChar = readChar();
x = nextChar;
if(x==46){ // if you encounter a dot while eating numbers we have a float
// See what the next character is
tempString += (char)x;
nextChar = readChar();
x = nextChar;
// while there are still numbers consume symbols
while((x>= 48)&&(x <=57)){
tempString += (char)x;
nextChar = readChar();
x = nextChar;
}
// once the while loop breaks, we are one symbol ahead and we have a token.
tempToken = new Token(tempString,"float", tempCharPos, lineNum);
tokenFoundFlag = true;
ptrAheadOneFlag = true;
break;
}
// if we never enter the float block we have a number
tempToken = new Token(tempString, "integer", tempCharPos, lineNum);
tokenFoundFlag = true;
ptrAheadOneFlag = true;
}
}// end of "number" | 5 |
@BeforeMethod
@Test(groups = { "Integer-Sorting", "Primitive Sort" })
public void testBubbleSortInt() {
Reporter.log("[ ** Bubble Sort ** ]\n");
try {
testSortIntegers = new BubbleSort<>(
primitiveShuffledArrayInt.clone());
Reporter.log("1. Unsorted Random Array\n");
timeKeeper = System.currentTimeMillis();
testSortIntegers.sortArray();
if (testSortIntegers.isSorted())
Reporter.log("Test Passed : ");
else
throw new TestException("Array was not sorted!!!");
Reporter.log((System.currentTimeMillis() - timeKeeper) + " ms\n");
Reporter.log("2. Sorted Random Array\n");
timeKeeper = System.currentTimeMillis();
testSortIntegers.sortArray();
if (testSortIntegers.isSorted())
Reporter.log("Test Passed : ");
else
throw new TestException("Array was not sorted!!!");
Reporter.log((System.currentTimeMillis() - timeKeeper) + " ms\n");
Reporter.log("3. Reversed Sorted Array\n");
ShuffleArray.reverseArray(testSortIntegers.getArray());
timeKeeper = System.currentTimeMillis();
testSortIntegers.sortArray();
if (testSortIntegers.isSorted())
Reporter.log("Test Passed : ");
else
throw new TestException("Array was not sorted!!!");
Reporter.log((System.currentTimeMillis() - timeKeeper) + " ms\n");
}
catch (Exception x) {
System.err.println(x);
throw x;
}
} | 4 |
public ArrayList<BookType> getAllBookType() {
ArrayList<BookType> ret = new ArrayList<BookType>();
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/librarysystem?user=admin&password=123456");
st=conn.createStatement();
//Select the book type
rs = st.executeQuery("SELECT * FROM BookType");
while(rs.next()) {
//Fill fields of the book type
BookType bt = new BookType();
bt.setTypeName(rs.getString("typeName"));
bt.setMaxReservation(rs.getInt("maxReservation"));
bt.setOverdueFee(rs.getInt("overdueFee"));
ret.add(bt);
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
finally
{
try {
if(conn != null)
conn.close();
if(st != null)
st.close();
if(rs != null)
rs.close();
} catch (Exception e) { }
}
return ret;
} | 6 |
public void buildingWeather(){
if (document != null) {
NodeList headerList = document.getElementsByTagName("header");
System.out.println("노드" + headerList.item(0).getChildNodes().getLength());
for (int i = 0; i< headerList.getLength(); i++){
// childNode
for (int k = 0; k < headerList.item(i).getChildNodes().getLength(); k++) {
if (headerList.item(i).getChildNodes().item(k).getNodeType() == Node.ELEMENT_NODE) {
System.out.print(k + ":" + headerList.item(i).getChildNodes().item(k).getNodeName() + "====>");
System.out.println(headerList.item(i).getChildNodes().item(k).getTextContent());
}
}
}
NodeList list = document.getElementsByTagName("data");
System.out.println("노드" + list.item(0).getChildNodes().getLength());
for (int i = 0; i < list.getLength(); i++) {
// System.out.println("===" + list.item(i).getAttributes().getNamedItem("seq").getTextContent() + "===");
// childNode
for (int k = 0; k < list.item(i).getChildNodes().getLength(); k++) {
if (list.item(i).getChildNodes().item(k).getNodeType() == Node.ELEMENT_NODE) {
// System.out.print(k + ":" + list.item(i).getChildNodes().item(k).getNodeName() + "====>");
// System.out.println(list.item(i).getChildNodes().item(k).getTextContent());
}
}
}
}
} | 7 |
public static String getMenuKeyValueStr() {
String s = "";
for (int i = 0; i < getMenuKeySymbolCount(); i++) {
s += menuSymbols[i].name;
if (i < getMenuKeySymbolCount() - 1)
s += ", ";
}
return s;
} | 2 |
private Location getRandomLocation(String location)
throws DestinationInvalidException {
double random = Math.random();
boolean above = false;
int x, y, z;
World world;
// Will it be a positive or negative number
if (random > 0.45D)
above = true;
else
above = false;
x = getRandomNumberRange(1, 10000);
y = getRandomNumberRange(1, 250);
z = getRandomNumberRange(1, 10000);
if (!above) {
// Make it a negative amount.
x = x - (x * 2);
z = z - (z * 2);
}
String worldName = location.replaceAll(".*\\(|\\).*", "");
// No world given. Select random world
if (worldName.trim().isEmpty() || !location.contains("(")
|| !location.contains(")")) {
List<World> worlds = plugin.getServer().getWorlds();
int randomWorld = getRandomNumberRange(0, (worlds.size() - 1));
world = worlds.get(randomWorld);
} else {
// World is specified. Search for world;
if (plugin.getServer().getWorld(worldName) == null) {
throw new DestinationInvalidException("World '" + worldName
+ "' for '" + location + "' does not exist!");
}
world = plugin.getServer().getWorld(worldName);
}
return new Location(world, x, y, z);
} | 6 |
private void createComboBox() {
comboBox = new JComboBox();
if (ProjectMainView.getCampaign().getQuizes().size()!=0) {
for (QuestPoint q : ProjectMainView.getCampaign().getQuizes()) {
comboBox.addItem(Integer.toString(q.getId()));
}
table.getColumnModel().getColumn(1);
}
comboBox.setVisible(false);
} | 2 |
public Typelignepl LignePl(Coords c) {
if (this.moveTo(Direction.UPLEFT).equals(c) || c.equals(this.moveTo(Direction.DOWNRIGHT))) {
return Typelignepl.DIAGONAL2;
} else if (this.moveTo(Direction.UPRIGHT).equals(c) || c.equals(this.moveTo(Direction.DOWNLEFT))) {
return Typelignepl.DIAGONAL1;
} else if (this.moveTo(Direction.RIGHT).equals(c) || c.equals(this.moveTo(Direction.LEFT))) {
return Typelignepl.HORIZONTAL;
} else {
return Typelignepl.NONADJACENT;
}
} | 6 |
public boolean sameConfig(ComputerPlay compareComputer) {
int i=0;
if(compareComputer.hasChecksums() && hasChecksums() && !sameChecksum(compareComputer.checksums)) {
return false;
}
Vector<PlayRule> compareComputerPlayRules = compareComputer.getPlayRules();
for(PlayRule rule:playRules) {
PlayRule compareRule = compareComputerPlayRules.get(i);
if(rule.getWeighting(true) != compareRule.getWeighting(true)) {
if(!rule.configDescriptor.equalsIgnoreCase(compareRule.configDescriptor)) {
Logger.info("Compare Computer: "+filename);
Logger.info("Play Rule: "+rule.configDescriptor + " != "+compareRule.configDescriptor);
}
return false;
}
i++;
}
i=0;
Vector<RecruitRule> compareComputerRecruitRules = compareComputer.getRecruitRules();
for(RecruitRule rule:recruitRules) {
RecruitRule compareRule = compareComputerRecruitRules.get(i);
if(rule.getWeighting(true) != compareRule.getWeighting(true)) {
if(!rule.configDescriptor.equalsIgnoreCase(compareRule.configDescriptor)) {
Logger.info("Compare Computer: "+filename);
Logger.info("Recruit Rule: "+rule.configDescriptor + " != "+compareRule.configDescriptor);
}
return false;
}
i++;
}
return true;
} | 9 |
boolean traverseItem(boolean next) {
Control[] children = parent._getChildren();
int length = children.length;
int index = 0;
while (index < length) {
if (children[index] == this)
break;
index++;
}
/*
* It is possible (but unlikely), that application code could have
* disposed the widget in focus in or out events. Ensure that a disposed
* widget is not accessed.
*/
if (index == length)
return false;
int start = index, offset = (next) ? 1 : -1;
while ((index = (index + offset + length) % length) != start) {
Control child = children[index];
if (!child.isDisposed() && child.isTabItem()) {
if (child.setTabItemFocus(next))
return true;
}
}
return false;
} | 8 |
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args){
if (cmd.getName().equalsIgnoreCase("kit")){
if (!(sender instanceof Player)) { // If sender isn't a player fail
sender.sendMessage("This command can Only be run by a player");
return false;
} else {
Player player = (Player) sender; //cast sender to player
if (Guards.perms.has(player, "guards.kit")) { //if player has perms
player.getInventory().clear(); //clear inventory
player.getInventory().setArmorContents(null); //clear armour
for (PotionEffect effect : player.getActivePotionEffects()) { //remove all potion effects
player.removePotionEffect(effect.getType());
}
plugin.kitItems.giveItemKit(player);
plugin.kitArmour.giveArmourKit(player);
plugin.kitPotion.kitPotionEffect(player); //give Potion effects
player.sendMessage(plugin.prefix + "Your Guard Kit has been Issued. Visit the Guard room to restock"); //send Confirmation
return true;
}
}
}
return false;
} | 4 |
public SimRace() {
cars = new Car[numberOfCars];
accident = new Accident(500, cars);
for (int i = 0; i < numberOfCars; i++) {
cars[i] = new Car(laps);
}
for (Car c : cars) {
c.start();
}
accident.run();
try {
for (int i = 0; i < cars.length; i++)
cars[i].join();
accident.join();
} catch (InterruptedException e) {
}
for(int i = 1; i <= cars.length; i++){
System.out.println("Car " + i + ": " + cars[i-1].totalTime + "ms, crashed: " + cars[i-1].crashed);
}
System.out.println("Crash occurred at: " + accident.crashOccuredAt + "ms");
} | 5 |
private JSlider getJSliderWordsCount() {
if (jSliderWordsCount == null) {
jSliderWordsCount = new JSlider();
jSliderWordsCount.setMinimum(5000);
jSliderWordsCount.setMaximum(150000);
jSliderWordsCount.setValue(50000);
jSliderWordsCount.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent arg0) {
jLabelMaxWords.setText("Max words: ("+jSliderWordsCount.getValue()+")");
}
});
jLabelMaxWords.setText("Max words: ("+jSliderWordsCount.getValue()+")");
}
return jSliderWordsCount;
} | 1 |
public static void main(String [] args)
{
// initialize student and class configuration data
int studentNumber = 0;
String studentName = "blank";
String studentHandle = "000000";
String className = "297D/";
String configFileName = "./configBatch.txt";
// System.out.println("configFileName: " + configFileName);
// set fixed paths and file names:
String path = "C:/Program Files/Java/jdk1.7.0_25/bin";
String sourcePath = "./src";
String testDataPath = sourcePath;
String argsFileName = testDataPath + "/args.txt";
String testInputFileName = testDataPath + "/TestInput.txt";
/* make sure set correctly
System.out.println("path: " + path);
System.out.println("sourcePath: " + sourcePath);
System.out.println("testDataPath: " + testDataPath);
System.out.println("argsFileName: " + argsFileName);
System.out.println("testInputFileName: " + testInputFileName);
*/
try
{
// config file has list of ordinal student number,
// student name, and random handle
File configFile = new File(configFileName);
Scanner in = new Scanner(configFile);
int runNumber = 1;
while(in.hasNextLine())
{
String line = in.nextLine();
Scanner inLine = new Scanner(line);
// debug code - print out scanned config info
// System.out.print("scanned config info: ");
while(inLine.hasNext())
{
studentNumber = inLine.nextInt();
studentName = inLine.next();
studentHandle = inLine.next();
}
// set paths and file names:
String classPath = "/java/bin/" + className + studentName;
String studentPath = sourcePath + "/" + studentName;
String inputFileStub = studentPath + "/input";
String outputFileName = studentPath + "/output-" + studentName + ".txt";
/* make sure set correctly
System.out.println("classPath: " + classPath);
System.out.println("studentPath: " + studentPath);
System.out.println("inputFileStub: " + inputFileStub);
System.out.println("outputFileName: " + outputFileName);
*/
System.out.println("run #: " + runNumber + " ; studentNumber: " + studentNumber +
"; Name: " + studentName + "; Handle: " + studentHandle);
System.out.println("Output goes to: " + outputFileName);
// run javac compiler - returns 0 on success
// Compiler Constructor:
// public Compiler(int numbr, String nme, String hndl, String pth, String clsPath,
// String srcPath, String stdPath, String outFileName)
Compiler c = new Compiler(runNumber, studentName, studentHandle, path, classPath, sourcePath,studentPath, outputFileName);
int success = c.compileJava();
// Print whether or not compile successful
if(success == 0)
{
System.out.println("Compiled Successfully");
}
else
{
System.out.println("Compile Failed");
}
// Run the test cases
// TestRunner consructor:
// public TestRunner(int numbr, String nme, String hndl, String pth, String clsPath,
// String srcPath, String stdPath, String tstDataPath, String argFileName,
// String tstInputFileName, String inputFileStub, String outFileName)
TestRunner r = new TestRunner(runNumber, studentName, studentHandle, path, classPath, sourcePath, studentPath, testDataPath, argsFileName, testInputFileName, inputFileStub, outputFileName);
r.runJava();
runNumber++;
System.out.println();
}
} catch(IOException ioe)
{
System.out.println("main IOException");
}
} | 4 |
public static void main(String[] args) {
try {
HttpURLConnection getConnection = (HttpURLConnection) (new URL(SERVLET_ADDRESS)).openConnection();
getConnection.setDoOutput(true);
getConnection.setDoInput(true);
getConnection.setInstanceFollowRedirects(false);
getConnection.setRequestMethod("GET");
File data = new File("LunchServiceData.xml");
if (!data.exists()) {
data.createNewFile();
}
BufferedReader dataReader = new BufferedReader(new InputStreamReader(getConnection.getInputStream()));
BufferedWriter dataWriter = new BufferedWriter(new FileWriter(data.getAbsoluteFile()));
Scanner userInput = new Scanner(System.in);
String readData;
readData = dataReader.readLine();
while (readData != null) {
dataWriter.write(readData);
readData = dataReader.readLine();
}
dataReader.close();
dataWriter.flush();
dataWriter.close();
getConnection.disconnect();
JAXBContext jaxbContext = JAXBContext.newInstance(LunchService.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
LunchService lunchService = (LunchService) unmarshaller.unmarshal(data);
List<Restaurant> restaurants = lunchService.getRestaurant();
System.out.println("Please input the restaurant number, then the menu item number:");
for (int i = 0; i < restaurants.size(); i++) {
Restaurant restaurant = restaurants.get(i);
System.out.printf("%d) %s%n", i + 1, restaurant.getName());
List<MenuItem> menuItems = restaurant.getMenuItem();
for (int j = 0; j < menuItems.size(); j++) {
MenuItem menuItem = menuItems.get(j);
System.out.printf("\t%d: %s - $%s%n", j + 1, menuItem.getName(), menuItem.getPrice());
}
}
int restaurantID = Integer.parseInt(userInput.nextLine()) - 1;
int menuItemID = Integer.parseInt(userInput.nextLine()) - 1;
HttpURLConnection postConnection = (HttpURLConnection) (new URL(ORDER_SERVLET_ADDRESS)).openConnection();
postConnection.setRequestMethod("POST");
postConnection.setDoOutput(true);
postConnection.setDoInput(true);
postConnection.setRequestProperty("Content-Type", "text/xml");
LunchService order = new LunchService();
Restaurant orderRestaurant = new Restaurant();
orderRestaurant.setName(lunchService.getRestaurant().get(restaurantID).getName());
MenuItem orderMenuItem = new MenuItem();
orderMenuItem.setName(lunchService.getRestaurant().get(restaurantID).getMenuItem().get(menuItemID).getName());
orderMenuItem.setPrice(lunchService.getRestaurant().get(restaurantID).getMenuItem().get(menuItemID).getPrice());
orderRestaurant.getMenuItem().add(orderMenuItem);
order.getRestaurant().add(orderRestaurant);
Marshaller marshaller = jaxbContext.createMarshaller();
OutputStreamWriter postWriter = new OutputStreamWriter(postConnection.getOutputStream());
marshaller.marshal(order, postWriter);
postWriter.flush();
postWriter.close();
String responseMessage = postConnection.getResponseMessage();
if (responseMessage != null){
System.out.println(responseMessage);
}
postConnection.disconnect();
System.out.println("Thank you for your order!");
} catch (Exception e) {
System.out.println("There was an error, sorry");
e.printStackTrace();
}
} | 6 |
public void solve(char[][] board) {
if(board==null || board.length<=1 || board[0].length<=1)
return;
//use flood fill method at edge rows and columns
//first and last rows
for(int i=0;i<board[0].length;i++)
{
fill(board,0,i); //flood fill starting from pos(0, i)
fill(board,board.length-1,i);
}
//first and last column
for(int i=0;i<board.length;i++)
{
fill(board,i,0);
fill(board,i,board[0].length-1);
}
//replace
for(int i=0;i<board.length;i++)
{
for(int j=0;j<board[0].length;j++)
{
if(board[i][j]=='O')
board[i][j]='X';
else if(board[i][j]=='#')
board[i][j]='O';
}
}
} | 9 |
public void draw(Graphics2D g2d) {
if (!isOutOfScreen) {
g2d.drawImage(img_movingSquare, (int) x, (int) y, null);
}
} | 1 |
public void registrar(ProxyClient cliente, String password){
String id="";
//BufferedImage image = (BufferedImage)((Image) cliente.icon.getImage());
Image source = cliente.icon.getImage();
int w = source.getWidth(null);
int h = source.getHeight(null);
BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = (Graphics2D)image.getGraphics();
g2d.drawImage(source, 0, 0, null);
g2d.dispose();
//TODO: MACBOOK
String url = "/Users/eduardoirias/Sites/RMI-Files/users/" + cliente.user+".png";
try {
ImageIO.write(image, "png",new File(url));
} catch (IOException ex) {
Logger.getLogger(MensajeImpl.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("Comenzando");
try {
Class.forName("com.mysql.jdbc.Driver");
// Setup the connection with the DB
connect = DriverManager
.getConnection("jdbc:mysql://localhost:8889/so2?"
+ "user=root&password=root");
System.out.println("Insertando");
System.out.println("Nombre: "+ cliente.lastName);
System.out.println("user: "+ cliente.user);
String url2 = "http://macbook-air-de-eduardo.local:8888/RMI-Files/users/" + cliente.user+".png";
// Result set get the result of the SQL query
preparedStatement = connect.prepareStatement("INSERT INTO so2.usuario (nombre,apellido,correo,user,password,photo) VALUE ('"+cliente.name+"','"
+ cliente.lastName+"','"+cliente.email+"','"+cliente.user+"','"+password+"','"+url2+"')");
preparedStatement.executeUpdate();
}catch (Exception e) {
try {
throw e;
} catch (Exception ex) {
Logger.getLogger(MensajeImpl.class.getName()).log(Level.SEVERE, null, ex);
}
} finally {
close();
}
try {
// This will load the MySQL driver, each DB has its own driver
Class.forName("com.mysql.jdbc.Driver");
// Setup the connection with the DB
connect = DriverManager
.getConnection("jdbc:mysql://localhost:8889/so2?"
+ "user=root&password=root");
System.out.println("CONECTADO!");
// Statements allow to issue SQL queries to the database
statement = connect.createStatement();
// Result set get the result of the SQL query
resultSet = statement.executeQuery("SELECT * FROM so2.usuario WHERE user = '" + cliente.user+"'");
while (resultSet.next()) {
// It is possible to get the columns via name
// also possible to get the columns via the column number
// which starts at 1
// e.g. resultSet.getSTring(2);
id = resultSet.getString("id");
//doTest();
}
} catch (Exception e) {
try {
throw e;
} catch (Exception ex) {
Logger.getLogger(MensajeImpl.class.getName()).log(Level.SEVERE, null, ex);
}
} finally {
close();
}
try {
Class.forName("com.mysql.jdbc.Driver");
// Setup the connection with the DB
connect = DriverManager
.getConnection("jdbc:mysql://localhost:8889/so2?"
+ "user=root&password=root");
System.out.println("Insertando");
System.out.println("Nombre: "+ cliente.name);
System.out.println("user: "+ cliente.user);
// Result set get the result of the SQL query
preparedStatement = connect.prepareStatement("INSERT INTO so2.usuarioperteneceaconversacion (idusuario,idconversacion) VALUE ('"+id+"','1')");
preparedStatement.executeUpdate();
}catch (Exception e) {
try {
throw e;
} catch (Exception ex) {
Logger.getLogger(MensajeImpl.class.getName()).log(Level.SEVERE, null, ex);
}
} finally {
close();
}
} | 8 |
public void updateRow(int index, Object[] array) {
// data[rowIndex][columnIndex] = (String) aValue;
EntityTransaction userTransaction = manager.getTransaction();
userTransaction.begin();
Project updateRecord = projectService.updateProject((String) array[0],
(String) array[1], (String) array[2], (String) array[3],
(String) array[4], (String) array[5], (String) array[6],
(String) array[7], (String) array[8], (String) array[9]);
userTransaction.commit();
// set the current row to rowIndex
int col = 0;
// update the data in the model to the entries in array
for (Object data : array) {
setValueAt((String) data, index, col++);
}
} | 1 |
public Node getNode(Node node, String nodeName) {
NodeList list = node.getChildNodes();
for (int i = 0; i < list.getLength(); i++) {
Node serverNode = list.item(i);
if (list.item(i).hasChildNodes() && list.item(i).getNodeName().equals(nodeName)) {
return serverNode;
}
}
return null;
} | 3 |
public void select(IWorkbenchPartReference toSelect) {
if(toSelect == null)
return;
clearSelection();
for (int i = 0; i < listItems.size(); i++) {
TabListItemWidget listItem = listItems.get(i);
if(listItem.has(toSelect)) {
selectedIndex = i;
if(selectedItem != null)
selectedItem.deselect();
selectedItem = listItem;
selectedItem.select();
return;
}
}
} | 4 |
public void addDownloadFileType(FileType fileType){
this.downloadFileTypes.add(fileType.getType());
} | 0 |
public void reborn(int oldAgentId, int newAgentId) {
/*古い様式のtraitsリストの中に最古のtraitが入っていた場合は、preferenceLengthの値を更新する必要がある可能性がある*/
Trait oldTrait = traitMap.get(oldAgentId);
traitMap.remove(oldAgentId); //古い様式をHashMapから取り除く
if (oldTrait.containsValue(OLDEST_TRAIT_NUM)) {
final int INFINITE = 10000; //わざと不正に大きな値
Iterator it = traitMap.keySet().iterator();
boolean isOtherOldestTrait = false;
int NEW_OLDEST_TRAIT_NUM = INFINITE;//わざと不正な値を入れておく
while (it.hasNext()) {
int agentId = (Integer) it.next();
Trait t = traitMap.get(agentId);
if (t.containsValue(OLDEST_TRAIT_NUM)) { //他のTraitがOLDEST_TRAIT_NUM番の様式を持っていた場合、preferenceLengthの値は更新する必要がない
isOtherOldestTrait = true;
break;
} else {
if (t.getSmallestValue() != -1) {
if (t.getSmallestValue() < NEW_OLDEST_TRAIT_NUM) {
NEW_OLDEST_TRAIT_NUM = t.getSmallestValue();
}
}
}
}
if (isOtherOldestTrait == false) { //この場合OLDEST_TRAIT_NUM番の様式は死滅したことになる
if (NEW_OLDEST_TRAIT_NUM != INFINITE) {
OLDEST_TRAIT_NUM = NEW_OLDEST_TRAIT_NUM;//新しい値
} else {
OLDEST_TRAIT_NUM = 0; //全エージェントのTraitが死滅。。。(ほぼありえないケースだが。。。)
}
}
}
/*traitsがない新しい様式を作成し、HashMapに代入する*/
Trait newTrait = new Trait(newAgentId, "reborn");
traitMap.put(newAgentId, newTrait);
} | 7 |
public Tile(int x, int y, int typeInt) {
tileX = x * 40;
tileY = y * 40;
type = typeInt;
r = new Rectangle();
if (type == 5) {
tileImage = StartingClass.tiledirt;
} else if (type == 8) {
tileImage = StartingClass.tilegrassTop;
} else if (type == 4) {
tileImage = StartingClass.tilegrassLeft;
} else if (type == 6) {
tileImage = StartingClass.tilegrassRight;
} else if (type == 2) {
tileImage = StartingClass.tilegrassBot;
} else {
type = 0;
}
} | 5 |
static final void method1760(int i, int i_0_, boolean bool, int i_1_,
byte i_2_, int i_3_, int i_4_, int i_5_) {
if (i_2_ > -85)
method1762(-14, 70, 13, -100);
anInt5940++;
if (((bool
? ((Class348_Sub51) BitmapTable.aClass348_Sub51_3959)
.aClass239_Sub26_7215.method1838(-32350)
: ((Class348_Sub51) BitmapTable.aClass348_Sub51_3959)
.aClass239_Sub26_7272.method1838(-32350))
^ 0xffffffff) != -1
&& i_3_ != 0 && (Message.anInt2021 ^ 0xffffffff) > -51 && i != -1)
Class258_Sub2.aClass10Array8531[Message.anInt2021++]
= new Class10(!bool ? (byte) 2 : (byte) 3, i, i_3_, i_5_, i_0_,
i_1_, i_4_, null);
} | 7 |
@Override
public boolean equals(Object o) {
if (o instanceof Matrix) {
Matrix m = (Matrix) o;
if (m.getWidth() == getWidth() && m.getHeight() == getHeight()) {
return Arrays.deepEquals(m.data, data);
}
}
return false;
} | 3 |
public Queue<String> doubleOsevenXMLUnit(){
try {
path = new File(".").getCanonicalPath();
FileInputStream file =
new FileInputStream(new File(path + "/xml/papabicho.xml"));
DocumentBuilderFactory builderFactory =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document xmlDocument = builder.parse(file);
XPath xPath = XPathFactory.newInstance().newXPath();
System.out.println("************************************");
String expression01 = "/Units/Unit[@class='007']";
NodeList nodeList;
Node node01 = (Node) xPath.compile(expression01)
.evaluate(xmlDocument, XPathConstants.NODE);
if(null != node01) {
nodeList = node01.getChildNodes();
for (int i = 0;null!=nodeList && i < nodeList.getLength(); i++){
Node nod = nodeList.item(i);
if(nod.getNodeType() == Node.ELEMENT_NODE){
System.out.println(nodeList.item(i).getNodeName()
+ " : " + nod.getFirstChild().getNodeValue());
list.append(nod.getFirstChild().getNodeValue());
}
}
}
System.out.println("************************************");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (XPathExpressionException e) {
e.printStackTrace();
}
return list;
} | 9 |
public String getArea() {
return Area;
} | 0 |
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(GestionDesMatchs.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(GestionDesMatchs.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(GestionDesMatchs.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(GestionDesMatchs.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new GestionDesMatchs().setVisible(true);
}
});
} | 6 |
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {
ActionErrors errors =new ActionErrors();
if (login.length()<3 && login.length()<30 )
{
errors.add("loginError", new ActionMessage("login.error"));
}
if (password.length()<3 && password.length()<30 )
{
errors.add("passwordError", new ActionMessage("password.error"));
}
return errors;
} | 4 |
public static Locale getLocale() {
XMLInputFactory xif = XMLInputFactory.newInstance();
XMLStreamReader in = null;
File options = FreeColDirectories.getClientOptionsFile();
if (options.canRead()) {
try {
in = xif.createXMLStreamReader(new FileInputStream(options), "UTF-8");
in.nextTag();
/**
* The following code was contributed by armcode to fix
* bug #[ 2045521 ] "Exception in Freecol.log on starting
* game". I was never able to reproduce the bug, but the
* patch did no harm either.
*/
for(int eventid = in.getEventType();eventid != XMLEvent.END_DOCUMENT; eventid = in.getEventType()) {
//TODO: Is checking for XMLEvent.ATTRIBUTE needed?
if (eventid == XMLEvent.START_ELEMENT) {
if (ClientOptions.LANGUAGE.equals(in.getAttributeValue(null, "id"))) {
return LanguageOption.getLocale(in.getAttributeValue(null, "value"));
}
}
in.nextTag();
}
//We don't have a language option in our file, it is either not there or the file is corrupt
logger.log(Level.WARNING, "Language setting not found in client options file. Using default.");
} catch (Exception e) {
logger.log(Level.WARNING, "Exception while loading options.", e);
} finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e) {
logger.log(Level.WARNING, "Exception while closing stream.", e);
}
}
}
return Locale.getDefault();
} | 7 |
private void checkFourOfAKind() {
for (int i = 0; i < 13; i++) {
if (getNumberOfValues(i) == 4) {
myEvaluation[0] = 8;
myEvaluation[1] = i;
myEvaluation[2] = i;
myEvaluation[3] = 0;// Find leftover card
break;
}
}
} | 2 |
@After
public void tearDown()
throws Exception
{
scheduler.shutdown();
} | 0 |
public void night() {
// End of simulation
endOfSimulation = true;
for (int i = 0; i < grid.getWidth(); i++) {
for (int j = 0; j < grid.getDepth(); j++) {
if (getSubject(i, j) == null) {
continue;
}
if (getSubject(i, j).getState() instanceof Dead) {
grid.place(null, j, i);
continue;
}
// Someone is still infected
if (getSubject(i, j).isInfected()) {
endOfSimulation = false;
}
// Incubation
getSubject(i, j).incubate();
}
}
} | 5 |
public boolean equals(Object _other)
{
if (_other == null) {
return false;
}
if (_other == this) {
return true;
}
if (!(_other instanceof BillPayeePk)) {
return false;
}
final BillPayeePk _cast = (BillPayeePk) _other;
if (billId != _cast.billId) {
return false;
}
if (userId != _cast.userId) {
return false;
}
if (billIdNull != _cast.billIdNull) {
return false;
}
if (userIdNull != _cast.userIdNull) {
return false;
}
return true;
} | 7 |
private JTextField getTxFieldArtistName() {
if (txFieldArtistName == null) {
txFieldArtistName = new JTextField();
txFieldArtistName.setText("Eminem");
txFieldArtistName.setBounds(10, 42, 86, 20);
txFieldArtistName.setColumns(10);
}
return txFieldArtistName;
} | 1 |
private String determineCurrentCategoryDependingOnGameboardPosition() {
int currentPos = currentPlayer.getGameboardPositions();
if (currentPos == 0) return CATEGORY_POP;
if (currentPos == 4) return CATEGORY_POP;
if (currentPos == 8) return CATEGORY_POP;
if (currentPos == 1) return CATEGORY_SCIENCE;
if (currentPos == 5) return CATEGORY_SCIENCE;
if (currentPos == 9) return CATEGORY_SCIENCE;
if (currentPos == 2) return CATEGORY_SPORTS;
if (currentPos == 6) return CATEGORY_SPORTS;
if (currentPos == 10) return CATEGORY_SPORTS;
return CATEGORY_ROCK;
} | 9 |
public String nextToken() throws JSONException {
char c;
char q;
StringBuffer sb = new StringBuffer();
do {
c = next();
} while (Character.isWhitespace(c));
if (c == '"' || c == '\'') {
q = c;
for (;;) {
c = next();
if (c < ' ') {
throw syntaxError("Unterminated string.");
}
if (c == q) {
return sb.toString();
}
sb.append(c);
}
}
for (;;) {
if (c == 0 || Character.isWhitespace(c)) {
return sb.toString();
}
sb.append(c);
c = next();
}
} | 9 |
final boolean method1534() {
boolean bool = Class348_Sub10.method2788() != 0;
if (!bool)
return false;
int i = anIntArray2726.length;
for (int i_42_ = 0; i_42_ < i; i_42_++)
anIntArray2721[i_42_] = anIntArray2726[i_42_];
int i_43_ = anIntArray2724[anInt2722 - 1];
int i_44_ = Class299.method2253(i_43_ - 1, -17);
anIntArray2728[0] = Class348_Sub10.method2789(i_44_);
anIntArray2728[1] = Class348_Sub10.method2789(i_44_);
int i_45_ = 2;
for (int i_46_ = 0; i_46_ < anIntArray2725.length; i_46_++) {
int i_47_ = anIntArray2725[i_46_];
int i_48_ = anIntArray2720[i_47_];
int i_49_ = anIntArray2729[i_47_];
int i_50_ = (1 << i_49_) - 1;
int i_51_ = 0;
if (i_49_ > 0)
i_51_ = Class348_Sub10.aClass370Array6718
[anIntArray2723[i_47_]].method3581();
for (int i_52_ = 0; i_52_ < i_48_; i_52_++) {
int i_53_ = anIntArrayArray2730[i_47_][i_51_ & i_50_];
i_51_ >>>= i_49_;
anIntArray2728[i_45_++]
= (i_53_ >= 0
? Class348_Sub10.aClass370Array6718[i_53_].method3581()
: 0);
}
}
return true;
} | 6 |
@Override
public void removeVisitor(MapleCharacter visitor) {
final byte slot = getVisitorSlot(visitor);
boolean shouldUpdate = getFreeSlot() == -1;
if (slot != -1) {
broadcastToVisitors(PlayerShopPacket.shopVisitorLeave(slot));
switch (slot) {
case 1:
chr1 = new WeakReference(null);
break;
case 2:
chr2 = new WeakReference(null);
break;
case 3:
chr3 = new WeakReference(null);
break;
}
if (shouldUpdate) {
if (getShopType() == 1) {
((HiredMerchant) this).getMap().broadcastMessage(PlayerShopPacket.updateHiredMerchant((HiredMerchant) this));
} else {
((MaplePlayerShop) this).getMCOwner().getMap().broadcastMessage(PlayerShopPacket.sendPlayerShopBox(((MaplePlayerShop) this).getMCOwner()));
}
}
}
} | 6 |
public void cadastraProfessor(String nome, String matricula)
throws ProfessorJaExisteException {
boolean teste = false;
for (Professor e : professores) {
if (e.getMatricula().equals(matricula)) {
teste = true;
break;
}
}
if (teste == false) {
Professor p = new Professor(nome, matricula);
professores.add(p);
} else {
throw new ProfessorJaExisteException("Professor Já cadastrado");
}
} | 3 |
private void getDataFromUserTable () {
try {
connection = DriverManager.getConnection(Utils.DB_URL);
statement = connection.createStatement();
resultSet = statement.executeQuery("SELECT id, name, date_created, date_lastlog FROM User");
while (resultSet.next()) {
userIdList.add(resultSet.getInt("id"));
nameList.add(resultSet.getString("name"));
regDateList.add(resultSet.getString("date_created"));
lastLogDateList.add(resultSet.getString("date_lastlog"));
}
} catch (SQLException e) {
e.printStackTrace();
}
finally {
try {
connection.close();
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
} | 3 |
public boolean exist(char[][] board, String word) {
int m = board.length;
int n = board[0].length;
if( word.length() == 0 ) return false;
if( m * n < word.length() ) return false;
for ( int i = 0; i < m; i++ ) {
for ( int j = 0; j < n; j++ ) {
if( board[i][j] == word.charAt(0) ) {
if( dfs( board, i, j, word, 0, null ) ) return true;
}
}
}
return false;
} | 6 |
public static void main(String[] args) {
String line;
BufferedWriter bufferedWriter = null;
// try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in))) {
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(inputFilePath))) {
bufferedWriter = new BufferedWriter(new FileWriter(outputFilePath));
line = bufferedReader.readLine(); //read T, numberOfTestCases
int numberOfTestCases = Integer.parseInt(line);
if(!checkNumberOfTestCases(numberOfTestCases)){
//invalid number of test cases
System.out.println("Invalid number of test cases entered. Program exiting.");
return;
}
for (int testCaseIndex = 1; testCaseIndex <= numberOfTestCases; testCaseIndex++) {
TestCase testCase = new TestCase(bufferedReader);
PerformanceResult performanceResult = testCase.solve();
StringBuilder sb = new StringBuilder();
sb.append("Case #");
sb.append(testCaseIndex);
sb.append(": ");
if (performanceResult.getMagicianJobPerformance() == MagicianJobPerformance.GOOD) {
sb.append(performanceResult.getCardList().get(0).getValue());
} else {
sb.append(performanceResult.getMagicianJobPerformance().getMessage());
}
// System.out.println(sb);
bufferedWriter.write(sb.toString());
bufferedWriter.newLine();
}
} catch (Exception e) {
System.out.println("Exception when using reader.");
e.printStackTrace();
} finally {
if (bufferedWriter != null) {
try {
bufferedWriter.flush();
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} | 6 |
private void getKeywordsInSentence(String sen, int index) {
Iterator<String> it = keywords.iterator();
while (it.hasNext()) {
String s = it.next();
if (sen.indexOf(s) != -1) {
if (!keywordExtracted.containsKey(s)) {
KeywordInfo ki = new KeywordInfo();
keywordExtracted.put(s, ki);
}
keywordExtracted.get(s).num++;
keywordExtracted.get(s).indexOfSentence.add(index);
}
}
} | 3 |
public boolean hit(int upcard, int total, boolean soft) {
if (soft) {
return total < 18 || (total == 18 && (upcard >= 9 || upcard == 1));
} else {
if (total < 12) return true;
if (upcard > 6 || upcard == 1) return total <= 16;
if (total > 12) return false;
return upcard <= 3;
}
} | 8 |
public static JSONObject toJSONObject(String string) throws JSONException {
JSONObject jo = new JSONObject();
HTTPTokener x = new HTTPTokener(string);
String token;
token = x.nextToken();
if (token.toUpperCase().startsWith("HTTP")) {
// Response
jo.put("HTTP-Version", token);
jo.put("Status-Code", x.nextToken());
jo.put("Reason-Phrase", x.nextTo('\0'));
x.next();
} else {
// Request
jo.put("Method", token);
jo.put("Request-URI", x.nextToken());
jo.put("HTTP-Version", x.nextToken());
}
// Fields
while (x.more()) {
String name = x.nextTo(':');
x.next(':');
jo.put(name, x.nextTo('\0'));
x.next();
}
return jo;
} | 2 |
public static void main(String args[]) {
/*
* Set the Nimbus look and feel
*/
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/*
* If Nimbus (introduced in Java SE 6) is not available, stay with the
* default look and feel. For details see
* http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(DaftarPembeli.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(DaftarPembeli.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(DaftarPembeli.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(DaftarPembeli.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/*
* Create and display the dialog
*/
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
DaftarPembeli dialog = new DaftarPembeli(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
} | 6 |
public void givePlayerOfflineXP(Player player) {
String SQL = "SELECT * FROM " + tblOfflineGains + " WHERE `player` = ? AND `world` = ?";
// plugin.info("givePlayerOfflineXP: " + player.getName() + " in " +
// player.getWorld().getName());
boolean deleteEntries = false;
Connection con = getSQLConnection();
PreparedStatement statement = null;
try {
statement = con.prepareStatement(SQL);
statement.setString(1, player.getName());
statement.setString(2, player.getWorld().getName());
ResultSet result = statement.executeQuery();
while (result.next()) {
// plugin.info("givePlayerOfflineXP " + result.getInt(4)
// +" from " + result.getString(5));
plugin.sendMessage(player, F("stGiveOfflineXP", result.getInt(4), result.getString(5)));
player.giveExp(result.getInt(4));
deleteEntries = true;
}
} catch (SQLException e) {
e.printStackTrace();
}
if (deleteEntries == true) {
SQL = "DELETE FROM " + tblOfflineGains + " WHERE `player` = ? AND `world` = ?;";
try {
statement = con.prepareStatement(SQL);
statement.setString(1, player.getName());
statement.setString(2, player.getWorld().getName());
statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
try {
statement.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
} | 5 |
public MicromouseFrameworkGUI() {
super("Micromouse Framework GUI");
JPanel panel = new JPanel(true);
panel.setLayout(new BorderLayout());
/*
* GRID: NORTH
*/
JPanel p1 = new JPanel(new GridLayout(1, 6, 2, 2));
// make combo box
// - label
JTextField titleText = new JTextField("Micromouse Framework GUI");
titleText.setFont(new Font("SansSerif", Font.BOLD, 15));
titleText.setEditable(false);
p1.add(titleText);
fileName = new JTextField("Please load file");
fileName.setEditable(false);
p1.add(fileName);
bFile = new JButton("Browse");
bFile.addActionListener(this);
p1.add(bFile);
/*
* GRID: WEST
*/
JPanel p2 = new JPanel(new GridLayout(3, 2, 2, 2));
// make bot info screen
// Print current direction of the bot
JTextField curDirecLable = new JTextField("Current Direction: ");
curDirecLable.setEditable(false);
p2.add(curDirecLable);
curDirecVal = new JTextField(newRun.getCurrentDirec());
curDirecVal.setEditable(false);
p2.add(curDirecVal);
// Print current location
JTextField curLocLable = new JTextField("Current Location: ");
curLocLable.setEditable(false);
p2.add(curLocLable);
curLocVal = new JTextField("( " + newRun.getCurLocX() + ", " + newRun.getCurLocY() + " )");
curLocVal.setEditable(false);
p2.add(curLocVal);
bStart = new JButton("Start");
bStart.addActionListener(this);
bStart.setEnabled(false);
p2.add(bStart);
// add next button
bNext = new JButton("Next");
bNext.addActionListener(this);
bNext.setEnabled(false);
p2.add(bNext);
/*
* GRID: CENTER
*/
JPanel p3 = new JPanel(new GridLayout(16, 16), true);
// make board GUI
board = new JButton[newRun.BOARD_MAX][newRun.BOARD_MAX];
for (int i = 0; i < newRun.BOARD_MAX; i++) {
for (int j = 0; j < newRun.BOARD_MAX; j++) {
board[i][j] = new JButton("" + newRun.getPotential(j, i));
board[i][j].setBackground(Color.green);
board[i][j].setOpaque(true);
p3.add(board[i][j]);
}
}
/*
* GRID: SOUTH
*/
// add dialogue
JPanel p5 = new JPanel(new GridLayout(1, 3, 5, 5));
dialogue = new JTextField();
dialogue.setEditable(false);
p5.add(dialogue);
// add reset droid button
bReset = new JButton("Reset Droid");
bReset.addActionListener(this);
p5.add(bReset);
// add clear all button
bClear = new JButton("Clear All");
bClear.addActionListener(this);
p5.add(bClear);
panel.add(p1, BorderLayout.NORTH);
panel.add(p2, BorderLayout.WEST);
panel.add(p3, BorderLayout.CENTER);
panel.add(p5, BorderLayout.SOUTH);
getContentPane().add(panel);
} | 2 |
private static void writeResults(HashMap<Long,HashMap<String,Holder>> map) throws Exception
{
BufferedWriter writer = new BufferedWriter(new FileWriter(new File(ConfigReader.getBurkholderiaDir()+
File.separator + "summary" + File.separator + "pivotedSNPS.txt")));
HashSet<String> strains= new HashSet<String>();
for( Long aLong : map.keySet() )
{
HashMap<String, Holder> innerMap = map.get(aLong);
for(String s : innerMap.keySet())
strains.add(s);
}
List<String> strainList = new ArrayList<String>();
for(String s : strains)
strainList.add(s);
Collections.sort(strainList);
writer.write("key");
for(String s : strainList)
writer.write("\t" + s);
writer.write("\n");
for( Long aLong : map.keySet() )
{
HashMap<String, Holder> innerMap = map.get(aLong);
writer.write("" + aLong);
for(String s: strainList)
writer.write("\t"+ innerMap.get(s));
writer.write("\n");
}
writer.flush(); writer.close();
} | 6 |
private static void addContigLayer(JsonObject root) throws Exception
{
List<JsonObject> list = new ArrayList<JsonObject>();
addNodeAndChildren(root, list);
System.out.println("Got " + list.size() + " flat nodes");
HashMap<Integer, List<JsonObject>> outerMap = new HashMap<Integer, List<JsonObject>>();
for(JsonObject json : list)
{
int genomicLevel = Integer.parseInt(json.getNameValuePairMap().get("contig"));
if(genomicLevel == 0)
{
if( ! json.getNameValuePairMap().get("name").equals("root") )
{
throw new Exception("Logic error");
}
}
else if (json.getNameValuePairMap().get("level").equals("operon"))
{
List<JsonObject> aList = outerMap.get(genomicLevel);
if( aList == null)
{
aList = new ArrayList<JsonObject>();
outerMap.put(genomicLevel, aList);
}
aList.add(json);
}
}
List<Integer> outerKeys = new ArrayList<Integer>(outerMap.keySet());
Collections.sort(outerKeys);
root.getChildren().clear();
if( root.getChildren().size() != 0)
throw new Exception("Could not clear list");
for( Integer i : outerKeys )
{
List<JsonObject> innerList = outerMap.get(i);
Collections.sort(innerList, new SortByPosition());
JsonObject jsonObject = new JsonObject();
jsonObject.makeNewEmptyChildrenList();
jsonObject.getChildren().addAll(innerList);
jsonObject.getNameValuePairMap().put("level", "contig");
jsonObject.getNameValuePairMap().put("name", "contig" + i);
jsonObject.getNameValuePairMap().put("log_pValue.il02.ilaom02", "0");
jsonObject.getNameValuePairMap().put("log_pValue.il12.ilaom12", "0");
jsonObject.getNameValuePairMap().put("log_pValue.il20.ilaom20", "0");
jsonObject.getNameValuePairMap().put("fc.il02.ilaom02", "0");
jsonObject.getNameValuePairMap().put("fc.il12.ilaom12", "0");
jsonObject.getNameValuePairMap().put("fc.il12.ilaom20", "0");
jsonObject.getNameValuePairMap().put("genomic.location", i + ".0");
jsonObject.getNameValuePairMap().put("contig", i + ".0");
jsonObject.getNameValuePairMap().put("position", "0");
root.getChildren().add(jsonObject);
}
} | 7 |
public static int drawMultiLineString(Graphics2D g2d, String text, int lineWidth, int x, int y) {
FontMetrics m = g2d.getFontMetrics();
int originalY = y;
if (m.stringWidth(text) < lineWidth) {
g2d.drawString(text, x, y);
} else {
String[] words = text.split(" ");
String currentLine = words[0];
for (int i = 1; i < words.length; i++) {
if (m.stringWidth(currentLine + words[i]) < lineWidth) {
currentLine += " " + words[i];
} else {
g2d.drawString(currentLine, x, y);
y += m.getHeight();
currentLine = words[i];
}
}
if (currentLine.trim().length() > 0) {
g2d.drawString(currentLine, x, y);
}
}
return y - originalY + m.getHeight();
} | 4 |
@Override
public boolean isDiagonalObstacle(Element elementPassingThrough, Element otherDiagonalElement) {
if (otherDiagonalElement instanceof LightTrailPart && isConnectedTo((LightTrailPart) otherDiagonalElement))
return true;
if (otherDiagonalElement instanceof Player && this.getPlayer().equals(otherDiagonalElement) && this.isHeadOfLightTrail())
return true;
return false;
} | 5 |
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
ChatColor yellow = ChatColor.YELLOW;
ChatColor red = ChatColor.RED;
if(args.length < 1) {
if(sender instanceof Player) {
Player player = (Player) sender;
if(player.hasPermission("CrazyFeet.crazymagic.automagic")) {
if(p.getAMagicPlayers().contains(player.getName())) {
p.getAMagicPlayers().remove(player);
p.getAMagicPlayers().saveAutoMagicPlayers();
player.sendMessage(yellow+"You will no longer have "+red+"CrazyMagic "+yellow+"enabled when joining!");
return true;
} else {
p.getAMagicPlayers().add(player);
p.getAMagicPlayers().saveAutoMagicPlayers();
player.sendMessage(yellow+"You will now have "+red+"CrazyMagic "+yellow+"enabled when joining!");
return true;
}
} else {
player.sendMessage(red+"No permission.");
return true;
}
} else {
sender.sendMessage(red+"You must be an ingame player to do this!");
return true;
}
} else if(args.length == 1) {
if(sender.hasPermission("CrazyFeet.crazymagic.automagicother")) {
if(Bukkit.getServer().getPlayer(args[0]) != null) {
Player targ = Bukkit.getServer().getPlayer(args[0]);
if(p.getAMagicPlayers().contains(targ.getName())) {
p.getAMagicPlayers().remove(targ);
p.getAMagicPlayers().saveAutoMagicPlayers();
targ.sendMessage(red+sender.getName()+yellow+" has enabled automatic "+red+"CrazyMagic"+yellow+" on you when you join!");
sender.sendMessage(red+targ.getDisplayName()+yellow+" now has automatic "+red+"CrazyMagic"+yellow+" when they join.");
return true;
} else {
p.getAMagicPlayers().remove(targ);
p.getAMagicPlayers().saveAutoMagicPlayers();
targ.sendMessage(red+sender.getName()+yellow+" has disabled automatic "+red+"CrazyMagic"+yellow+" on you when you join!");
sender.sendMessage(red+targ.getDisplayName()+yellow+" no longer has automatic "+red+"CrazyMagic"+yellow+" when they join.");
return true;
}
} else {
sender.sendMessage(red+"The player "+yellow+args[0]+red+" is either offline or does not exist!");
return true;
}
} else {
sender.sendMessage(red+"No permission");
return true;
}
} else {
sender.sendMessage(red+"Incorrect usage. Use /crazyfeet for help!");
return true;
}
} | 8 |
public static Campaign getCampaign() {
return campaign;
} | 0 |
public Node getHeadNode(int linkedListLength){
if(linkedListLength<=0){
return null;
}
node.setData(count);
node.setNextNode(null);
prevNode = node;
for(int i=2;i<=linkedListLength;i++){
count++;
currNode = new Node();
currNode.setData(count);
currNode.setNextNode(null);
prevNode.setNextNode(currNode);
prevNode = currNode;
}
return node;
} | 2 |
public void serve() {
if (preSubmitted.isEmpty() && activeEngines.isEmpty()) {
return;
}
if (!preSubmitted.isEmpty()) {
Iterator<Engine> it = preSubmitted.iterator();
while (it.hasNext()) {
Engine engine = it.next();
if (!engine.isRunning()) {
engine.setRunning(true);
activeEngines.add(engine);
engine.fire();
} else {
activeEngines.add(engine);
}
it.remove();
}
}
Iterator<Engine> it2 = activeEngines.iterator();
while (it2.hasNext()) {
Engine engine = it2.next();
if (activeEngines.isEmpty()) {
return;
}
if (!engine.isRunning()) {
it2.remove();
engine = null;
}
}
} | 8 |
public DataProvider()
{
this.datasets = new ArrayList<DataSet>();
} | 0 |
@SuppressWarnings("unused")
public void move(){
if(!motionLock){
double stepX;
double stepY;
double angle;
stepX = new Random().nextInt(3);
stepY = new Random().nextInt(3);
while(!(posX + stepX > 0) &&
!(posX + stepX < settings.screenWidth - 40) &&
!(posY + stepY > 0) &&
!(posY + stepY < (settings.screenWidth / 2) - 40)){
stepX = new Random().nextInt(6) - 3;
stepY = new Random().nextInt(6) - 3;
}
posX += stepX;
posY += stepY;
/* if(hasTarget){
double dx = posX - target[0];
double dy = posY - target[1];
if(dx > 0){
angle = Math.atan(dy / dx);
}else{
angle = Math.atan(dy / dx) + Math.PI;
}
stepX = new Random().nextInt(3);
stepY = new Random().nextInt(3);
posX += stepX;
posY += stepY;
isNearTarget = isNearTarget();
if(isNearTarget()){
hasTarget = false;
}
}else{
generateRandomTarget();
} */ // WIP Code
}
} | 5 |
public static List<List<Integer>> generate(int numRows) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
for (int i = 0; i < numRows; i++) {
List<Integer> l = new ArrayList<Integer>();
for (int j = 0; j < i + 1; j++) {
if (0 == i || 0 == j || i == j) {
l.add(1);
} else {
l.add(res.get(i - 1).get(j - 1) + res.get(i - 1).get(j));
}
}
res.add(l);
}
return res;
} | 5 |
public void kasitteleKayttajanKomento()
{
switch(kayttajanKomento)
{
case SIIRTO_VASEMMALLE: siirraTetriminoa(Suunta.VASEN); break;
case SIIRTO_OIKEALLE: siirraTetriminoa(Suunta.OIKEA); break;
case KAANTAMINEN: kaannaTetriminoa(Suunta.OIKEA); break;
case PUDOTTAMINEN: pudotaTetrimino(); break;
case TAUOTTAMINEN:
this.pelitilanteenPiirtaja.paivitaTilanne();
if(pelitilanne.onTauolla())
pelitilanne.jatkaPelia();
else
pelitilanne.tauota();
break;
case UUSI_PELI: alustaUusiPeli(); break;
}
kayttajanKomento = Komento.EI_KOMENTOA;
} | 7 |
private void validateOveractivePolling(
final int index,
final StubConnection conn,
final StubConnection previous) {
BOSHClient session = client.get();
if (session == null || previous == null) {
// No established session
return;
}
ComposableBody prevReq =
toComposableBody(previous.getRequest().getBody());
ComposableBody req =
toComposableBody(conn.getRequest().getBody());
String prevIDStr = prevReq.getAttribute(Attributes.RID);
String idStr = req.getAttribute(Attributes.RID);
long prevID = Long.parseLong(prevIDStr);
long id = Long.parseLong(idStr);
if (!(prevReq.getPayloadXML().isEmpty()
&& req.getPayloadXML().isEmpty())
&& (id - prevID != 1)) {
// Not two consecutive empty requests
return;
}
ComposableBody prevResp =
toComposableBody(previous.getResponse().getBody());
if (!prevResp.getPayloadXML().isEmpty()) {
// Previous response was not empty
return;
}
CMSessionParams params = session.getCMSessionParams();
if (params == null) {
// Nothing to validate against
return;
}
AttrPolling polling = params.getPollingInterval();
if (polling == null) {
// Nothing to check against
return;
}
long prevTime = previous.getRequest().getRequestTime();
long connTime = conn.getRequest().getRequestTime();
long delta = connTime - prevTime;
if (delta < polling.getInMilliseconds() ) {
fail("Polling session overactivity policy violation in "
+ "connection #" + index + " (" + delta + " < "
+ polling.getInMilliseconds() + ")");
}
} | 9 |
protected void endGame(int status) {
if(gameEnded) {
this.running = false;
}
else {
gameEnded = true;
if(pauseScreen != null && !pauseScreen.isDestroyed()) {
pauseScreen.canDraw = false;
pauseScreen.destroy();
}
GameEntity.destroyAll();
gameOver = new GameOverScreen(status);
}
} | 3 |
private void getAllRooms(){
Document doc = getXmlFile();
NodeList nList = doc.getElementsByTagName("Location");
if(debugConsole){
System.out.println("Locations in XML-File");
System.out.println("-------------------");
System.out.println("");
System.out.println("Number : "+nList.getLength());
System.out.println("");
}
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
Element eElement = (Element) nNode;
Room room = new Room(Integer.parseInt(eElement.getElementsByTagName("Value").item(9).getTextContent()));
if(debugConsole){
System.out.println("Location: " + eElement.getAttribute("ID"));
System.out.println("--------");
}
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
room.setName(eElement.getElementsByTagName("Value").item(0).getTextContent());
room.setPicturePath(eElement.getElementsByTagName("Value").item(1).getTextContent());
room.setDescription(eElement.getElementsByTagName("Value").item(2).getTextContent());
room.setAct(eElement.getElementsByTagName("Value").item(3).getTextContent());
room.setChapter(eElement.getElementsByTagName("Value").item(4).getTextContent());
room.setScene(eElement.getElementsByTagName("Value").item(5).getTextContent());
room.setFunction(eElement.getElementsByTagName("Value").item(6).getTextContent());
room.setFloor(eElement.getElementsByTagName("Value").item(7).getTextContent());
room.setMood(eElement.getElementsByTagName("Value").item(8).getTextContent());
room.setLocationId(eElement.getElementsByTagName("Value").item(9).getTextContent());
room.setGameObjectsIncluded(eElement.getElementsByTagName("Value").item(10).getTextContent());
room.setNpcs(eElement.getElementsByTagName("Value").item(11).getTextContent());
if(!(eElement.getElementsByTagName("Value").item(12).getTextContent().isEmpty())){
room.setLocationPointer(Integer.parseInt(eElement.getElementsByTagName("Value").item(12).getTextContent().substring(11,14)));
}
if(debugConsole){
System.out.println("Name : " + eElement.getElementsByTagName("Value").item(0).getTextContent());
System.out.println("Picture path (?) : " + eElement.getElementsByTagName("Value").item(1).getTextContent());
System.out.println("Description : " + eElement.getElementsByTagName("Value").item(2).getTextContent());
System.out.println("Act : " + eElement.getElementsByTagName("Value").item(3).getTextContent());
System.out.println("Chapter : " + eElement.getElementsByTagName("Value").item(4).getTextContent());
System.out.println("Scene : " + eElement.getElementsByTagName("Value").item(5).getTextContent());
System.out.println("Floor : " + eElement.getElementsByTagName("Value").item(6).getTextContent());
System.out.println("Function : " + eElement.getElementsByTagName("Value").item(7).getTextContent());
System.out.println("Location ID : " + eElement.getElementsByTagName("Value").item(8).getTextContent());
System.out.println("GameObjectsIncluded : " + eElement.getElementsByTagName("Value").item(9).getTextContent());
System.out.println("NPCs : " + eElement.getElementsByTagName("Value").item(10).getTextContent());
System.out.println("");
}
}
listRooms.add(room);
}
} | 6 |
public int lastIndexOf(Attributes attributeList) {
for (int i = size - 1; i >= 0; i--) {
if (attributeLists[i] == attributeList) {
return i;
}
}
return -1;
} | 2 |
Subsets and Splits
SQL Console for giganticode/java-cmpx-v1
The query retrieves a limited number of text entries within a specific length range, providing basic filtering but minimal analytical insight.