method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
8c2fa28e-1d05-414a-8e58-b5f8e7fd06c8 | 5 | public Boolean selectTests(Connection con, Triple t){
try{
ResultSet rs = con.select("SELECT ?s ?p ?o FROM <http://example.com> WHERE {?s ?p ?o} LIMIT 1");
int i =0;
while(rs.next()){
if(! rs.getObject(1).toString().equals(t.getSubject().toString()))
return false;
if(! rs.getObject(2).toString().equals(t.getPredicate().toString()))
return false;
// assertEquals(rs.getObject(3).toString(), t.getObject().toString());
i++;
}
if(i>0){
return true;
}
return false;
}catch(SQLException e){
e.printStackTrace();
assertTrue(false);
}
return null;
} |
696ca957-d0fe-43eb-8861-2bb5cc4013b9 | 2 | public void collectCallbackMethodsIncremental() {
Transform transform = new Transform("wjtp.ajc", new SceneTransformer() {
protected void internalTransform(String phaseName, @SuppressWarnings("rawtypes") Map options) {
// Process the worklist from last time
System.out.println("Running incremental callback analysis for " + callbackWorklist.size()
+ " components...");
Map<String, Set<AndroidMethod>> workListCopy = new HashMap<String, Set<AndroidMethod>>
(callbackWorklist);
for (Entry<String, Set<AndroidMethod>> entry : workListCopy.entrySet()) {
List<MethodOrMethodContext> entryClasses = new LinkedList<MethodOrMethodContext>();
for (AndroidMethod am : entry.getValue())
entryClasses.add(Scene.v().getMethod(am.getSignature()));
analyzeRechableMethods(Scene.v().getSootClass(entry.getKey()), entryClasses);
callbackWorklist.remove(entry.getKey());
}
System.out.println("Incremental callback analysis done.");
}
});
PackManager.v().getPack("wjtp").add(transform);
} |
224adfa2-9b4f-4d2f-84a2-0c2a0ff1db58 | 3 | @Override
public void caseAThisHexp(AThisHexp node)
{
for(int i=0;i<indent;i++) System.out.print(" ");
indent++;
System.out.println("(This");
inAThisHexp(node);
if(node.getThis() != null)
{
node.getThis().apply(this);
}
outAThisHexp(node);
indent--;
for(int i=0;i<indent;i++) System.out.print(" ");
System.out.println(")");
} |
c3de657d-ad44-487f-b9b9-ca4a1232244f | 8 | public void findIndexUsageForPair(TablePairActivity tablePair) {
for (Query query : queries) {
List<String> queryRelations = query.getRelations();
Set<QueryFilter> queryFilters = query.getSelections();
String tableA = tablePair.getNameOfTableA();
String tableB = tablePair.getNameOfTableB();
if (tablePair.isPair() && queryRelations.contains(tableA)
&& queryRelations.contains(tableB)) {
// check queries that contain both of the tables
for (QueryFilter qf : queryFilters) {
QueryAttribute qa = qf.getLeftAttribute();
// if the query uses a unique index, then that table is
// credited with the number of times the query appears
if (db.isUniqueKey(qa.getTableName(), qa.getColumnName())) {
if (qa.getTableName().equals(tableA)) {
tablePair.addUsageIndexA(query.getTimesUsed());
} else if (qa.getTableName().equals(tableB)) {
tablePair.addUsageIndexB(query.getTimesUsed());
}
}
}
}
}
} |
438ae5cd-d645-4034-8f7d-e0bdfdccccad | 9 | public static void main(String args[]) throws IOException {
//Input server check
System.out.println("Is this the server?");
Scanner sysIn = new Scanner(System.in);
String inToken = sysIn.nextLine();
if(inToken.equalsIgnoreCase("yes")) {
isServer = true;
}
else {
isServer = false;
}
try {
//Open up the connection
Socket socket = null;
ServerSocket server = null;
if(isServer) {
System.out.println("Starting");
server = new ServerSocket(4001);
System.out.println("Waiting for client");
socket = server.accept();
System.out.println("Server has connected.");
}
else {
System.out.println("Client connecting");
socket = new Socket("Travis-PC", 4001);
}
//Create the writer and reader
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
if(isServer) {
System.out.println("Enter rows");
int rows = sysIn.nextInt();
System.out.println("Enter columns");
int columns = sysIn.nextInt();
System.out.println("Enter max time");
maxTime = sysIn.nextInt();
sysIn.nextLine();
System.out.println("Enter B or W");
inToken = sysIn.next();
send("WELCOME");
send("INFO " + columns + " " + rows + " " + inToken + " " + maxTime);
board = new Board(rows, columns);
if(inToken.equals("W")) {
ai = new AI(Color.WHITE, (long)(maxTime * .95));
}
else {
ai = new AI(Color.BLACK, (long)(maxTime * .95));
}
}
//The execution loop
while(!gameOver) {
readAndExecute();
}
System.out.println(victoryState);
//Close the sockets
out.close();
socket.close();
if(isServer) {
server.close();
}
} catch (UnknownHostException e) {
System.out.println("Don't know about host");
} catch (IOException e) {
System.out.println("Could get IO connection");
} catch (BadBoardException e) {
e.printStackTrace();
}
} |
f19e2f03-8f9c-4a58-bfcd-42c626b41e98 | 7 | @Override
public boolean add(E e) {
setIn = new Node(e);
Node previous = null;
if(isEmpty()){
root = setIn;
ant++;
return true;
}
current = root;
while(current != null){
if(setIn.object.compareTo(current.object)<0){
previous = current;
current = current.right;
}else if(setIn.object.compareTo(current.object)>0){
previous = current;
current = current.left;
}else if(setIn.object.compareTo(current.object)==0){
return false;
}
}
if(previous.object.compareTo(setIn.object)<0){
previous.right = setIn;
}else if(previous.object.compareTo(setIn.object)>0){
previous.left = setIn;
}
ant++;
return true;
} |
9bfb5ba7-f8ee-426e-9445-9bdbff74a45a | 8 | public static double[][] getInverse(double[][] A){
if(A.length != A[0].length)
return null;
if(getDet(A) == 0)
return null;
double T[][] = new double[A.length][A.length*2];
double I[][] = generateIdentity(A.length);
for(int i = 0; i<A.length; i++){
for(int j = A.length; j<T[0].length; j++){
T[i][j] = I[i][j-A.length];
}
for(int j = 0; j<A.length; j++){
T[i][j] = A[i][j];
}
}
T = rowReduce(T, A.length);
for(int i = 0; i<A.length; i++){
for(int j = A.length; j<T[0].length; j++){
if(T[i][j] == -0)
T[i][j] = T[i][j]*-1;
I[i][j-A.length] = T[i][j];
}
}
return I;
} |
d14b5a2d-522a-4f66-9a52-272c480663d6 | 2 | public static String trimFront(String text, String match, int numToTrim) {
int substringStart = 0;
for (int i = 0; i < numToTrim; i++) {
if (text.startsWith(match, substringStart)) {
substringStart += match.length();
}
}
return text.substring(substringStart, text.length());
} |
7bf23cf9-cad9-48b4-b6a8-9f91b913e7f8 | 6 | protected void quickSort(int low, int high, List<Player> players) {
int i = low;
int j = high;
Hand pivot = players.get(low + (high - low) / 2).getHands().get(0);
while (i <= j) {
while (players.get(i).getHands().get(0).compareTo(pivot) < 0)
i++;
while (players.get(j).getHands().get(0).compareTo(pivot) > 0)
j--;
if (i <= j) {
Collections.swap(players, i, j);
i++;
j--;
}
}
if (low < j)
quickSort(low, j, players);
if (i < high)
quickSort(i, high, players);
} |
6299491f-9c75-4c95-9436-3eef93132774 | 3 | private void generateLabelledDescription() throws Exception {
Description originalDescription = super.getDescription();
labelledDescription = Description
.createSuiteDescription(originalDescription.getDisplayName());
ArrayList<Description> childDescriptions = originalDescription
.getChildren();
int childCount = childDescriptions.size();
if (childCount != labels.size()) {
throw new Exception(
"Number of labels and number of parameters must match.");
}
for (int i = 0; i < childDescriptions.size(); i++) {
Description childDescription = childDescriptions.get(i);
String label = labels.get(i);
Description newDescription = Description
.createSuiteDescription(label);
ArrayList<Description> grandChildren = childDescription
.getChildren();
for (Description grandChild : grandChildren) {
newDescription.addChild(grandChild);
}
labelledDescription.addChild(newDescription);
}
} |
1fd6a22a-82c4-4d6f-84fe-3cd166bd5407 | 3 | public static void disposeall(GL gl) {
Collection<Integer> dc;
synchronized (disposed) {
dc = disposed.get(gl);
if (dc == null)
return;
}
synchronized (dc) {
if (dc.isEmpty())
return;
int[] da = new int[dc.size()];
int i = 0;
for (int id : dc)
da[i++] = id;
dc.clear();
gl.glDeleteTextures(da.length, da, 0);
}
} |
950751ae-f221-4026-a9ab-0d5fc6b7ad8b | 3 | public ListNode reverse(ListNode head) {
if (head == null || head.next == null)
return head;
ListNode p = head.next;
head.next = null;
while (p != null) {
ListNode nextP = p.next;
p.next = head;
head = p;
p = nextP;
}
return head;
} |
8a020e27-4e24-457b-aba8-b5ead92558eb | 8 | private int jjMoveStringLiteralDfa5_0(long old0, long active0)
{
if (((active0 &= old0)) == 0L)
return jjMoveNfa_0(0, 4);
try { curChar = input_stream.readChar(); }
catch(java.io.IOException e) {
return jjMoveNfa_0(0, 4);
}
switch(curChar)
{
case 48:
return jjMoveStringLiteralDfa6_0(active0, 0x875e00000000000L);
case 53:
return jjMoveStringLiteralDfa6_0(active0, 0x200000000000000L);
case 55:
return jjMoveStringLiteralDfa6_0(active0, 0x88000000000000L);
case 57:
return jjMoveStringLiteralDfa6_0(active0, 0x102000000000000L);
case 67:
return jjMoveStringLiteralDfa6_0(active0, 0x400000000000000L);
case 99:
return jjMoveStringLiteralDfa6_0(active0, 0x400000000000000L);
default :
break;
}
return jjMoveNfa_0(0, 5);
} |
e9f20234-625c-4166-a105-ca5089dfbaec | 0 | public int fight() {
/*int damage = random.nextInt(maxDmg - (minDmg + 1)) + minDmg;
if(random.nextInt(100) < this.luck)
{
System.out.println("Critical Attack!");
return (int) damage * 2;
}*/
return (int) this.strength;
} |
9d638033-65d6-4753-a2f7-17434459f09b | 6 | private void createFictionalState() {
State fictionalState = new State(states.length, false);
for (Character ch : alphavet) {
fictionalState.addNextState(ch, fictionalState);
}
boolean flag = alphavet.contains('e');
if (flag) {
alphavet.remove('e');
}
for (State state : states) {
for (Character ch : alphavet) {
if (state.getNextState(ch) == null) {
state.addNextState(ch, fictionalState);
}
}
}
if (flag) {
alphavet.add('e');
}
} |
1b4a0def-7d3e-4bc8-ad67-9889402217be | 7 | public int getDistance() {
// check preconditions
int m = s1.length();
int n = s2.length();
if (m == 0) {
return n; // some simple heuristics
} else if (n == 0) {
return m; // some simple heuristics
} else if (m > n) {
String tempString = s1; // swap m with n to get O(min(m, n)) space
s1 = s2;
s2 = tempString;
int tempInt = m;
m = n;
n = tempInt;
}
// normalize case
s1 = s1.toUpperCase();
s2 = s2.toUpperCase();
// Instead of a 2d array of space O(m*n) such as int d[][] = new int[m +
// 1][n + 1], only the previous row and current row need to be stored at
// any one time in prevD[] and currD[]. This reduces the space
// complexity to O(min(m, n)).
int prevD[] = new int[n + 1];
int currD[] = new int[n + 1];
int temp[]; // temporary pointer for swapping
// the distance of any second string to an empty first string
for (int j = 0; j < n + 1; j++) {
prevD[j] = j;
}
// for each row in the distance matrix
for (int i = 0; i < m; i++) {
// the distance of any first string to an empty second string
currD[0] = i + 1;
char ch1 = s1.charAt(i);
// for each column in the distance matrix
for (int j = 1; j <= n; j++) {
char ch2 = s2.charAt(j - 1);
if (ch1 == ch2) {
currD[j] = prevD[j - 1];
} else {
currD[j] = minOfThreeNumbers(prevD[j] + 1,
currD[j - 1] + 1, prevD[j - 1] + 1);
}
}
temp = prevD;
prevD = currD;
currD = temp;
}
// after swapping, the final answer is now in the last column of prevD
return prevD[prevD.length - 1];
} |
a149a216-bd15-4b17-b089-4398b0291bd4 | 3 | private void conditional() throws CompilationException {
binOP(0);
if (type==35) { // '?'
int ecol=ct_column;
nextToken();
int stackSizeBeforeBranch=paramOPs.size();
conditional();
consumeT(36); // ':'
int stackSizeAfterFirstBranch=paramOPs.size();
conditional();
err_col=ecol; // report errors against '?'
if (Debug.enabled)
Debug.check((paramOPs.size()==stackSizeAfterFirstBranch+1) &&
(stackSizeAfterFirstBranch==stackSizeBeforeBranch+1),
"Stack in conditional branches is not balanced.");
paramOPs.push(new OPcondtnl(paramOPs));
};
}; |
2673ebad-40da-4c91-9b0e-c7eb4d19e3de | 9 | private void testAbstractMethods(ByteMatcher matcher) {
// test methods from abstract superclass
assertEquals("length is one", 1, matcher.length());
assertEquals("matcher for position 0 is this", matcher, matcher.getMatcherForPosition(0));
try {
matcher.getMatcherForPosition(-1);
fail("expected an IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException expectedIgnore) {}
try {
matcher.getMatcherForPosition(1);
fail("expected an IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException expectedIgnore) {}
assertEquals("reversed is identical", matcher, matcher.reverse());
assertEquals("subsequence of 0 is identical", matcher, matcher.subsequence(0));
try {
matcher.subsequence(-1);
fail("expected an IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException expectedIgnore) {}
try {
matcher.subsequence(1);
fail("expected an IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException expectedIgnore) {}
assertEquals("subsequence of 0,1 is identical", matcher, matcher.subsequence(0,1));
try {
matcher.subsequence(-1, 1);
fail("expected an IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException expectedIgnore) {}
try {
matcher.subsequence(0, 2);
fail("expected an IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException expectedIgnore) {}
int count = 0;
for (ByteMatcher itself : matcher) {
count++;
assertEquals("Iterating returns same matcher", matcher, itself);
}
assertEquals("Count of iterated matchers is one", 1, count);
Iterator<ByteMatcher> it = matcher.iterator();
try {
it.remove();
fail("Expected UnsupportedOperationException");
} catch (UnsupportedOperationException expectedIgnore) {}
it = matcher.iterator();
try {
assertTrue(it.hasNext());
it.next();
assertFalse(it.hasNext());
it.next();
fail("Expected NoSuchElementException");
} catch (NoSuchElementException expectedIgnore) {}
} |
cd6fd62f-646c-4723-8db3-5262557c527e | 9 | public void checkBanks() {
try {
File dir = new File("characters");
if(dir.exists()) {
String read;
File files[] = dir.listFiles();
for (int j = 0; j < files.length; j++) {
File loaded = files[j];
if (loaded.getName().endsWith(".txt")) {
Scanner s = new Scanner (loaded);
int cash = 0;
while (s.hasNextLine()) {
read = s.nextLine();
if (read.startsWith("character-item") || read.startsWith("character-bank")) {
String[] temp = read.split("\t");
int token1 = Integer.parseInt(temp[1]);
int token2 = Integer.parseInt(temp[2]);
if (token1 == 996) {
cash += token2;
if (cash > 12500000) {
System.out.println("name: " + loaded.getName());
}
}
}
}
}
}
} else {
System.out.println("FAIL");
}
} catch (Exception e) {
e.printStackTrace();
}
} |
7a982881-8505-4431-ab98-a6af5f203753 | 4 | public boolean requestEnter(Story st){
boolean isTrueStory = building.getElevator().getCurrentStory().equals(dispatchStory);
boolean isBoading = building.getElevator().getAction().equals(Actions.BOARDING);
if (gui.isAborted()){
setTransportationState(TransportationState.ABORTED);
return true;
} else if (isNotTriedEnter && isTrueStory && isBoading){
boolean isPermitEnter = building.getElevator().getController().permitEnter(st,this);
return isPermitEnter;
} else {
return false;
}
} |
8226ec37-9023-4192-9f71-23ae134d9710 | 1 | public boolean nemfoglalt()
{
if(sajat[hovaakar1][hovaakar2]==0)
return true;
logger.info("A lépés foglalt mezőre lépne!");
return false;
} |
c4638096-daeb-49d8-ba27-fbe7ee771518 | 0 | final void init() throws IOException {
receivingSocket = new MulticastSocket(4446);
multicastAddre = InetAddress.getByName("230.0.0.1");
receivingSocket.joinGroup(multicastAddre);
receiverThread = new MulticastReceiverThread();
sendSocket = new MulticastSocket(4446);
sendSocket.joinGroup(multicastAddre);
receiverThread.start();
} |
b2e337e5-0b12-4a03-83ae-13ea83e03d97 | 8 | @Override
public void setImages() {
if (waitImage == null) {
File imageFile = new File(Structure.baseDir + "BeachBetrayal.png");
try {
waitImage = ImageIO.read(imageFile);
} catch (IOException e) {
e.printStackTrace();
}
}
if (attackImage == null) { // cannot attack
File imageFile = new File(Structure.baseDir + "error.png");
try {
attackImage = ImageIO.read(imageFile);
} catch (IOException e) {
e.printStackTrace();
}
}
if (upgradeImage == null) { // cannot upgrade
File imageFile = new File(Structure.baseDir + "error.png");
try {
upgradeImage = ImageIO.read(imageFile);
} catch (IOException e) {
e.printStackTrace();
}
}
if (explodeImage == null) {
File imageFile = new File(Structure.baseDir
+ "explosion-sprite40.png");
try {
explodeImage = ImageIO.read(imageFile);
} catch (IOException e) {
e.printStackTrace();
}
}
} |
76b84aa7-3799-4a10-9957-de342376bd46 | 6 | public void update(GameContainer gcan, StateBasedGame state, int delta) throws SlickException
{
mx = Mouse.getX();
my = 720 - Mouse.getY();
Point t = mouseToIso();
isox = (int) t.getY();
isoy = (int) t.getX();
a.update();
b.update();
c.update();
d.update();
if(a.activated())
{
SessionSettings.ingame = false;
state.enterState(0, new FadeOutTransition(Color.black, 250), new FadeInTransition(Color.black, 250));
}
if(d.activated())
{
state.enterState(3, new FadeOutTransition(Color.black, 250), new FadeInTransition(Color.black, 250));
}
if(i.isKeyDown(i.KEY_A))
rtx += camerapancoefficient;
if(i.isKeyDown(i.KEY_D))
rtx -= camerapancoefficient;
if(i.isKeyDown(i.KEY_W))
rty += camerapancoefficient;
if(i.isKeyDown(i.KEY_S))
rty -= camerapancoefficient;
} |
e7905788-a85d-4aeb-a704-cad6632adb55 | 9 | static final void method1252(int i, int i_2_, int i_3_, int i_4_, int i_5_,
int i_6_, int i_7_, byte i_8_, int i_9_) {
anInt2124++;
if (!Class320.method2547(i_2_, (byte) 84)) {
if (i_4_ == -1) {
for (int i_10_ = 0; (i_10_ ^ 0xffffffff) > -101; i_10_++)
Class152.aBooleanArray2076[i_10_] = true;
} else
Class152.aBooleanArray2076[i_4_] = true;
} else {
int i_11_ = 0;
int i_12_ = 0;
int i_13_ = 0;
int i_14_ = 0;
int i_15_ = 0;
if (Class59_Sub1.aBoolean5300) {
i_11_ = AbtractArchiveLoader.anInt3941;
i_15_ = FileIndexRequest.anInt10463;
i_13_ = AbtractArchiveLoader.anInt3939;
i_12_ = Class239.anInt3142;
i_14_ = Class348_Sub3.anInt6585;
FileIndexRequest.anInt10463 = 1;
}
if (Class369_Sub2.aClass46ArrayArray8584[i_2_] == null)
Class348_Sub40_Sub7.method3064(i_9_, i, i_4_ < 0, i_5_, i_3_,
i_4_, i_6_, false,
(Class348_Sub40_Sub33
.aClass46ArrayArray9427[i_2_]),
-1, i_7_);
else
Class348_Sub40_Sub7.method3064(i_9_, i,
(i_4_ ^ 0xffffffff) > -1, i_5_,
i_3_, i_4_, i_6_, false,
(Class369_Sub2
.aClass46ArrayArray8584[i_2_]),
-1, i_7_);
if (i_8_ <= 58)
anInt2127 = -84;
if (Class59_Sub1.aBoolean5300) {
if ((i_4_ ^ 0xffffffff) <= -1
&& FileIndexRequest.anInt10463 == 2)
Class338.method2663(-5590, AbtractArchiveLoader.anInt3941,
AbtractArchiveLoader.anInt3939, Class239.anInt3142,
Class348_Sub3.anInt6585);
FileIndexRequest.anInt10463 = i_15_;
AbtractArchiveLoader.anInt3939 = i_13_;
Class239.anInt3142 = i_12_;
Class348_Sub3.anInt6585 = i_14_;
AbtractArchiveLoader.anInt3941 = i_11_;
}
}
} |
c99275db-4932-4d8e-9011-deb1993cbc96 | 0 | public void setAgentColor(Color c) {
agentColor = c;
} |
0920a41a-7bf3-4b7a-aa1e-ffee68959f86 | 0 | public SimpleMultiReplacementFileContentsHandler(Vector matches, Vector replacements, String lineEnding) {
super(lineEnding);
setMatches(matches);
setReplacements(replacements);
} |
0ee58d40-5936-424a-a502-0af24fa3a89e | 6 | public void keyPressed(KeyEvent e) {
if (e.getKeyModifiersText(e.getModifiers()).equals("Alt")) {
int arg = 0;
try {
arg = Integer.parseInt(e.getKeyText(e.getKeyCode()));
} catch (NumberFormatException ex) {
return;
}
switch (arg) {
case 1: //settlement
gameLogic._sideBar._exchangers.get(0).steal();
break;
case 2: // road
gameLogic._sideBar._exchangers.get(1).steal();
break;
case 3: // dev
gameLogic._sideBar._exchangers.get(2).steal();
break;
case 4: // city
gameLogic._sideBar._exchangers.get(3).steal();
break;
default:
break;
}
}} |
f360b7e6-75c3-47fd-bf28-02702475c55c | 6 | public List<String> parse(final String line) {
final List<String> list = new ArrayList<>();
final Matcher m = csvRE.matcher(line);
// For each field
while (m.find()) {
String match = m.group();
if (match == null) {
break;
}
if (match.endsWith(",")) { // trim trailing ,
match = match.substring(0, match.length() - 1);
}
if (match.startsWith("\"")) { // must also end with \"
if (!match.endsWith("\"")) {
throw new IllegalArgumentException(
"Quoted column missing end quote: " + line);
}
match = match.substring(1, match.length() - 1);
}
if (match.length() == 0) {
match = "";
}
list.add(match);
}
return list;
} |
378aecf4-b2c8-4721-be82-b9173035009c | 9 | private void doClear(button[][] mineButtons, int x, int y) throws Exception {
System.out.println("x:" + x + " y:" + y);
if (x < 0 || x >= 10 || y < 0 || y >= 10) {
return;
}
button currButton = mineButtons[x][y];
if (!currButton.isEnabled()) {
return;
}
currButton.setBackground(Color.lightGray);
currButton.setEnabled(false);
if (mineButtons[x][y].getIsBomb() == true) {
// end game in this if statement
time.stop();
currButton.setText("X");
// currButton.setIconImage("mineRed.png");
endGame(0, true);
System.out.println("clicked on button with bomb, exiting...");
// end game
} else {
// every time when a button is "cleared", increment variable
mines.incCleared();
// check if player has won the game if 90 buttons are cleared
System.out.println("currently, number of buttosn cleared: "
+ mines.getCleared());
if (mines.getCleared() == 90) {
System.out.println("commencing end game check");
endGameCheck();
}
if (mineButtons[x][y].getAdjacentBombs() != 0) {
// if (mineButtons[x][y].getAdjacentBombs() == 1) {
// currButton.setForeground(Color.BLUE);
// }
// else if (mineButtons[x][y].getAdjacentBombs() == 2) {
// currButton.setForeground(Color.GREEN);
// }
// else if (mineButtons[x][y].getAdjacentBombs() == 3) {
// currButton.setForeground(Color.RED);
// }
mineButtons[x][y].setText(mineButtons[x][y]
.getAdjacentBombsString());
} else {
mineButtons[x][y].setText("");
}
if (currButton.getAdjacentBombs() == 0) {
doClear(mineButtons, x - 1, y - 1); // top left
doClear(mineButtons, x, y - 1); // top middle
doClear(mineButtons, x + 1, y - 1); // top right
doClear(mineButtons, x - 1, y); // mid left
doClear(mineButtons, x + 1, y); // mid right
doClear(mineButtons, x - 1, y + 1); // bot left
doClear(mineButtons, x, y + 1); // bot middle
doClear(mineButtons, x + 1, y + 1); // bot right
}
}
} |
ee4ee304-4302-4edb-8c70-ef3c8b6dbff3 | 9 | private void internalDecompose(CharSequence source, StringBuffer target) {
StringBuffer buffer = new StringBuffer(8);
boolean canonical = (form & COMPATIBILITY_MASK) == 0;
int ch32;
//for (int i = 0; i < source.length(); i += (ch32<65536 ? 1 : 2)) {
for (int i = 0; i < source.length();) {
buffer.setLength(0);
//ch32 = UTF16.charAt(source, i);
ch32 = source.charAt(i++);
if (UTF16CharacterSet.isHighSurrogate(ch32)) {
char low = source.charAt(i++);
ch32 = UTF16CharacterSet.combinePair((char)ch32, low);
}
data.getRecursiveDecomposition(canonical, ch32, buffer);
// add all of the characters in the decomposition.
// (may be just the original character, if there was
// no decomposition mapping)
int ch;
//for (int j = 0; j < buffer.length(); j += (ch<65536 ? 1 : 2)) {
for (int j = 0; j < buffer.length();) {
//ch = UTF16.charAt(buffer, j);
ch = buffer.charAt(j++);
if (UTF16CharacterSet.isHighSurrogate(ch)) {
char low = buffer.charAt(j++);
ch = UTF16CharacterSet.combinePair((char)ch, low);
}
int chClass = data.getCanonicalClass(ch);
int k = target.length(); // insertion point
if (chClass != 0) {
// bubble-sort combining marks as necessary
int ch2;
while (k > 0) {
int step = 1;
ch2 = target.charAt(k-1);
if (UTF16CharacterSet.isSurrogate(ch2)) {
step = 2;
char high = target.charAt(k-2);
ch2 = UTF16CharacterSet.combinePair(high, (char)ch2);
}
if (data.getCanonicalClass(ch2) <= chClass) break;
k -= step;
}
// for (; k > 0; k -= (ch2<65536 ? 1 : 2)) {
// ch2 = UTF16.charAt(target, k-1);
// if (data.getCanonicalClass(ch2) <= chClass) break;
// }
}
if (ch < 65536) {
target.insert(k, (char)ch);
} else {
char[] chars = new char[]{UTF16CharacterSet.highSurrogate(ch), UTF16CharacterSet.lowSurrogate(ch)};
target.insert(k, chars);
}
//target.insert(k, UTF16.valueOf(ch));
}
}
} |
3c4b3e91-8e01-4af0-9d6a-874e4054e762 | 9 | public static boolean isValid(String IP){
IP = IP.trim();
if(IP.startsWith(".") || IP.endsWith(".")){
return false;
}
String[] ipArr = IP.split("\\.");
if(ipArr.length == 4){
for(String str : ipArr){
if(str.length() >= 0 && str.length() <=3){
try
{
int val= Integer.parseInt(str);
if(val < 0 && val > 255){
return false;
}
}
catch(NumberFormatException nfe)
{
return false;
}
}else{
return false;
}
}
}else{
return false;
}
return true;
} |
6a064b61-b826-48ce-ab5d-ea092ea2a6dd | 3 | public URL getCodeBase() {
if (Signlink.mainapp != null) {
return Signlink.mainapp.getCodeBase();
}
try {
if (super.frame != null) {
return new URL("http://127.0.0.1:" + (80 + Client.portOff));
// return new URL("http://ss-pk.no-ip.biz:" + 43594);
}
} catch (Exception exception) {
}
return super.getCodeBase();
} |
4e2ce816-86bd-4feb-a84c-411b862ff411 | 1 | public Item getItem(){
Item item;
if (originalItem==null)
item=new Item();
else item=originalItem;
item.setName(nameTextField.getText());
item.setDescription(descriptionTextField.getText());
item.setPrice(Integer.parseInt(priceTextField.getText()));
item.setQuantity(Integer.parseInt(quantityTextField.getText()));
return item;
} |
3789dfa1-9e09-4e48-9b66-9c9378a5f6cc | 4 | private static void displayReviewVideo(BufferedReader reader, VideoStore videoStore) {
try {
System.out.println("Please enter the title of the video you want review:");
String isbn = getISBNFromTitle(reader, videoStore, reader.readLine());
if (videoStore.getOwnReviews(isbn, 1).size() == 1) {
System.out.println("You have already reviewed this video.");
return;
}
System.out.println("Please enter your review score (0 = Terrible, 10 = Masterpiece):");
int score = readInt(reader, 0, 10);
String review = null;
System.out.println("Please enter your review (optional):");
try {
review = reader.readLine();
} catch (Exception e) {
e.printStackTrace();
}
if (videoStore.reviewVideo(isbn, score, review)) {
System.out.println("Successfully added the review for the video.");
return;
}
System.out.println("Could not successfully add the review for the video.");
} catch (Exception e) {
System.out.println("There was an error while creating the review.");
}
} |
b1d2e3f1-75ca-4b48-89f3-2c3bdfb2f948 | 1 | @Override
public void registerEvent(Class<? extends Event> clazz) {
} |
d0f755d6-1120-497c-a684-13cd5143aeb5 | 0 | public String getEmail() {
return email;
} |
3e07d284-a514-48a3-9bd1-cdfa01d5ec2d | 5 | void remove()
{
if ( left == null || right == null )
{
if ( this.left != null )
this.left.right = this.right;
if ( this.right != null )
this.right.left = this.left;
if ( this == parent.diagonals )
parent.diagonals = this.left;
}
// only destroy if we are on the edge
} |
fe353532-1794-464b-bc22-07b95d939dd6 | 2 | public static String trimSlashes(String s)
{
String temp = s;
if (temp.charAt(0) == DELIMITER.charAt(0)) temp = temp.substring(1);
if (temp.charAt(temp.length() - 1) == DELIMITER.charAt(0)) temp = temp.substring(0, temp.length() - 1);
return temp;
} |
306d4e12-9fa9-4713-a450-358245b3ae80 | 6 | @Override
public Node beforeDecode(mxCodec dec, Node node, Object into)
{
if (into instanceof mxChildChange)
{
mxChildChange change = (mxChildChange) into;
if (node.getFirstChild() != null
&& node.getFirstChild().getNodeType() == Node.ELEMENT_NODE)
{
// Makes sure the original node isn't modified
node = node.cloneNode(true);
Node tmp = node.getFirstChild();
change.setChild(dec.decodeCell(tmp, false));
Node tmp2 = tmp.getNextSibling();
tmp.getParentNode().removeChild(tmp);
tmp = tmp2;
while (tmp != null)
{
tmp2 = tmp.getNextSibling();
if (tmp.getNodeType() == Node.ELEMENT_NODE)
{
// Ignores all existing cells because those do not need
// to be re-inserted into the model. Since the encoded
// version of these cells contains the new parent, this
// would leave to an inconsistent state on the model
// (ie. a parent change without a call to
// parentForCellChanged).
String id = ((Element) tmp).getAttribute("id");
if (dec.lookup(id) == null)
{
dec.decodeCell(tmp, true);
}
}
tmp.getParentNode().removeChild(tmp);
tmp = tmp2;
}
}
else
{
String childRef = ((Element) node).getAttribute("child");
change.setChild(dec.getObject(childRef));
}
}
return node;
} |
05723630-efe5-4370-b7f1-d3596408bec3 | 8 | @Override
public Result run() {
Result result = null;
try {
Equals<Double> criterion = this.getCriterion();
Function<Double, Double> value = this.getFunction();
double goalValue = this.getGoalValue();
int maxIter = this.getMaximumIterations();
double x_1 = this.getInitialValue().getLowerBound();
double fx_1 = value.value(x_1);
if (criterion.value(fx_1, goalValue))
return new SuccessWithValue(x_1);
double x = this.getInitialValue().getUpperBound();
double fx = value.value(x);
if (criterion.value(fx, goalValue))
return new SuccessWithValue(x);
int iter;
for (iter = 0; iter < maxIter &&
!criterion.value(fx, goalValue); iter++) {
double n = x - (fx - goalValue) * (x - x_1) / (fx - fx_1);
double fn = value.value(n);
x_1 = x;
fx_1 = fx;
if (x == n)
result = new ResolutionNotFineEnough(value,
new IntervalReal(
Math.min(x_1, n), Interval.EndType.Includes,
Math.max(x_1, n), Interval.EndType.Includes),
goalValue);
x = n;
fx = fn;
}
if (result == null) {
if (maxIter <= iter)
result = new MaximumIterationsFailure(iter);
else
result = new IterativeSuccess(iter, x);
}
}
catch (Exception e) {
result = new UnhandledExceptionThrown(e);
}
return result;
} |
10daf08a-2e02-4d35-b5fb-6b3af6ca9a4f | 4 | public byte[] toByteArray(){
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = null;
try {
out = new ObjectOutputStream(bos);
out.writeObject(this);
return bos.toByteArray();
}catch(Exception e){e.printStackTrace(); return null;}
finally {
try {if (out != null) {out.close();}} catch (IOException ex) {}
try {bos.close();} catch (IOException ex) {}
}
} |
f2aefbe6-3809-45bf-bae8-07e0fdf0fc9f | 8 | @Override
public void process(OurSim ourSim) {
Peer peer = ourSim.getGrid().getObject(peerId);
if (!peer.isUp()) {
return;
}
PeerRequest request = peer.getRequest(requestSpec.getId());
if (request == null && !repetition) {
request = new PeerRequest(requestSpec,
requestSpec.getBrokerId());
peer.addRequest(request);
}
if (request == null || request.isPaused()) {
return;
}
if (request.isCancelled()) {
request.setCancelled(false);
return;
}
List<Allocation> allocables = AllocationHelper.getAllocationsForLocalRequest(peer, request);
for (Allocation allocable : allocables) {
dispatchAllocation(request, peer, allocable, requestSpec.getBrokerId(), ourSim);
}
if (request.getNeededWorkers() > 0) {
forwardRequestToCommunity(peer, request, ourSim);
request.setCancelled(false);
Event requestWorkersEvent = ourSim.createEvent(PeerEvents.REQUEST_WORKERS,
getTime() + ourSim.getLongProperty(
Configuration.PROP_REQUEST_REPETITION_INTERVAL),
peerId, requestSpec, true);
ourSim.addEvent(requestWorkersEvent);
}
} |
e71d21c5-774e-4c39-97cd-4ce91ffd491b | 3 | private Tag findInSuggestedTags(String value) {
if (suggestedTags != null) {
for (Tag tag : suggestedTags) {
if (tag.getTag().equalsIgnoreCase(value)) {
return tag;
}
}
}
return null;
} |
14dbba79-590c-46b5-bb77-2752a1f0bf04 | 8 | public String createPortOutput(int port, boolean resolve) {
String output = "";
if (port == 0)
return "0";
if (tcpServices != null) {
if ((port < 1024) && resolve) {
// try to resolve port number into clear text
if ((tcpServices != null) && (output=tcpServices[(int)port-1]) != null) {
} else if ((udpServices != null) && (output=udpServices[(int)port-1]) != null) {
} else
output = "" + port;
} else
output = "" + port;
} else
output = "" + port;
return output;
} |
47e0b291-6ff7-44d8-b139-19ef1cfff8fe | 8 | public HitResult hit(int StartX, int StartY, int EndX, int EndY, Vector<GameElement> Elements)
{
HitResult Result = new HitResult();
Result.setHit(false);
Result.setHitElement(null);
while(StartX != EndX || StartY != EndY)
{
if(StartX > EndX)
{
StartX--;
}
else if(StartX < EndX)
{
StartX++;
}
if(StartY > EndY)
{
StartY--;
}
else if(StartY < EndY)
{
StartY++;
}
for(GameElement element : Elements)
{
if(element.getBounds().contains(StartX, StartY))
{
Result.setHit(true);
Result.setHitElement(element);
return Result;
}
}
}
return Result;
} |
04096987-f30e-4b3d-88d1-f81e91a46b8f | 5 | private void method45() {
aBoolean1031 = true;
for (int j = 0; j < 7; j++) {
anIntArray1065[j] = -1;
for (int k = 0; k < IdentityKit.length; k++) {
if (IdentityKit.designCache[k].aBoolean662 || IdentityKit.designCache[k].anInt657 != j + (aBoolean1047 ? 0 : 7)) {
continue;
}
anIntArray1065[j] = k;
break;
}
}
} |
083d493b-6ed8-4fed-9d9d-836b560bf4dd | 5 | public String getFullName() {
String title = this.title == null ? "" : this.title.trim();
String firstName = this.firstName == null ? "" : this.firstName.trim();
String middleName = this.middleName == null ? "" : this.middleName.trim();
String lastName = this.lastName == null ? "" : this.lastName.trim();
String suffix = this.suffix == null ? "" : this.suffix.trim();
return title.concat(firstName).concat(middleName).concat(lastName).concat(suffix);
} |
aaa9b824-fe50-4395-b346-e943bae63830 | 1 | public void restoreHealth(String userName){
try {
cs = con.prepareCall("{call SET_HEALTH_TO_MAX(?)}");
cs.setString(1, userName);
cs.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
} |
f2449d8e-87ad-4712-a56f-ffbeb22398fa | 1 | public static void print(int array[]){
System.out.println("****************Sort Array***************");
for(int i = 0; i < array.length;i++){
System.out.print(array[i] +" ");
}
System.out.println();
} |
11d039f3-e60a-4c05-9943-d1a1f6eb5e87 | 7 | private int calculateNotAppropriateWorkingDaysForTeacherIIIAndIV() {
int penaltyPoints = 0;
List<LinkedHashMap> teachersAllDay = getAllDaysTeacherTimeTable();
for (LinkedHashMap<String, LinkedHashMap> daysTimeTable : teachersAllDay) {
// Very dirty hack because of rush
int weekDayNumber = teachersAllDay.indexOf(daysTimeTable);
Days weekDay = decideWeekDay(weekDayNumber);
Collection<String> teacherNames = daysTimeTable.keySet();
teacher:
for (String teacherName : teacherNames) {
LinkedHashMap<String, String> teachersTimeTableForTheDay = daysTimeTable.get(teacherName);
Collection<String> lectureNumbers = teachersTimeTableForTheDay.keySet();
for (String lectureNumber : lectureNumbers) {
String groupNameToSplit = teachersTimeTableForTheDay.get(lectureNumber);
String[] splittedGroupNames = groupNameToSplit.split(":");
String groupName = splittedGroupNames[1].trim();
if (!StringUtils.equals(groupName, EMPTY_GROUP)) {
if (studentsMockData.getTeachersFromIIIAndIV().containsKey(teacherName)) {
if (studentsMockData.getTeachers().get(teacherName).getFreeDays() != null
&& studentsMockData.getTeachers().get(teacherName).getFreeDays().contains(weekDay)) {
penaltyPoints += PenaltyPoints.BAD_WORKING_DAYS_FOR_TEACHER_III_IV.penaltyPoints();
continue teacher;
}
}
}
}
}
}
return penaltyPoints;
} |
151a7d94-8664-4855-ac12-3af712a1acc9 | 2 | public void salvarSQL(String destino) {
String str[];
str = this.getSQL(this.src);
Formatter saida = null;
try {
saida = new Formatter(destino);
saida.flush();
for (int i = 0; i < str.length; i++) {
saida.format("%s ;\n\n", str[i]);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(MainControlador.class.getName()).log(Level.SEVERE, null, ex);
}
saida.close();
} |
c7d97d10-1806-4046-a64a-6c1823c1badf | 0 | public String getItemcode() {
return this.itemcode;
} |
1d9b8598-168e-43c8-b25b-46995c3e89c3 | 8 | private StringBuilder getSectionFoto() throws ClassNotFoundException, SQLException {
StringBuilder sb = new StringBuilder();
sb.append("<div class=\"bs-docs-section\">");
Utils.appendNewLine(sb);
sb.append("<h1 id=\"foto\" class=\"page-header\">Fotogaléria</h1>");
Utils.appendNewLine(sb);
List<Gallery> galleries = this.ref.getGalleries();
for (Gallery gallery : galleries) {
// Gallery header
if (gallery.getName().length() > 0) {
sb.append("<h3 id=\"foto");
sb.append(gallery.getId());
sb.append("\">");
sb.append(gallery.getName());
sb.append("</h3>");
Utils.appendNewLine(sb);
}
if (gallery.hasPhotos()) {
// Gallery photos row - start
sb.append("<div class=\"row\">");
Utils.appendNewLine(sb);
List<GalleryPhoto> photos = gallery.getPhotos();
int pocet = 0;
for (GalleryPhoto photo : photos) {
pocet++;
// Photo column - start
sb.append("<div class=\"col-xs-6 col-sm-4 col-md-3 text-center\">");
Utils.appendNewLine(sb);
// Photo - thumbnail
sb.append("<a href=\"");
sb.append(gallery.getUrl());
sb.append(photo.getFileName());
sb.append("\"");
sb.append(" class=\"thumbnail\"");
sb.append(" style=\"margin-bottom: 5px;\"");
//TODO hardcoded pp ID
sb.append(" rel=\"prettyPhoto[pp1]\"");
sb.append(" title=\"");
sb.append(photo.getTitle());
sb.append("\"><img src=\"");
sb.append(gallery.getUrl());
sb.append(photo.getFileName());
sb.append("\" alt=\"");
sb.append(photo.getTitle());
sb.append("\"></a>");
Utils.appendNewLine(sb);
// Photo - description
sb.append("<p class=\"small\">");
sb.append(photo.getTitle());
sb.append("</p>");
Utils.appendNewLine(sb);
// Photo column - end
sb.append("</div>");
Utils.appendNewLine(sb);
if (pocet % 2 == 0) {
// clearfix for extra small devices (2 fotky na riadok)
sb.append("<div class=\"clearfix visible-xs\"></div>");
Utils.appendNewLine(sb);
}
if (pocet % 3 == 0) {
// clearfix for small devices (3 fotky na riadok)
sb.append("<div class=\"clearfix visible-sm\"></div>");
Utils.appendNewLine(sb);
}
if (pocet % 4 == 0) {
// clearfix for medium devices (4 fotky na riadok)
sb.append("<div class=\"clearfix visible-md\"></div>");
Utils.appendNewLine(sb);
}
if (pocet % 4 == 0) {
// clearfix for large devices (4 fotky na riadok)
sb.append("<div class=\"clearfix visible-lg\"></div>");
Utils.appendNewLine(sb);
}
}
// Gallery photos row - end
sb.append("</div>");
Utils.appendNewLine(sb);
}
sb.append(this.getSubGalleries(gallery));
}
sb.append("</div>");
Utils.appendNewLine(sb);
return sb;
} |
e8eb5363-cb2d-4080-80ed-1e23edccb68e | 4 | protected Class loadClass(String name, boolean resolve)
throws ClassFormatError, ClassNotFoundException {
name = name.intern();
synchronized (name) {
Class c = findLoadedClass(name);
if (c == null)
c = loadClassByDelegation(name);
if (c == null)
c = findClass(name);
if (c == null)
c = delegateToParent(name);
if (resolve)
resolveClass(c);
return c;
}
} |
7ca79c3e-9225-4df2-9473-32709d4d3928 | 1 | public JScrollPane getScrollPane_1() {
if (scrollPane_1 == null) {
scrollPane_1 = new JScrollPane();
scrollPane_1.setViewportView(getTaChat());
}
return scrollPane_1;
} |
a1bc886e-f1d7-4c6d-9b3f-6c4eb1ba9a2d | 8 | private ArrayList<Point> aStarSearch(Point location, Point destination, Campus campus)
{
int traveled = 0;
PriorityQueue<CPoint> frontier = new PriorityQueue<CPoint>();
ArrayList<Point> solution = new ArrayList<Point>();
ArrayList<Point> observations;
HashMap<Integer,Point> explored = new HashMap<Integer,Point>();
Point start = location;
Point end = destination;
explored.put(start.hashCode(), start);
Point current = start;
solution.add(start);
while (!(solution.get(0).equals(start) && solution.get(solution.size()-1).equals(end)))
{
observations = campus.getAdjacent(current);
if (observations.size() == 0)
{ System.out.println("Impossible destination.");
return null;
}
else if (observations.size() >= 1)
{
for (Point p : observations)
{ if (explored.get(p.hashCode()) == null)
{ double heuristic = Math.pow((Math.pow((end.x-p.x), 2) + Math.pow((end.y-p.y), 2)),.5);
frontier.add(new CPoint(p, heuristic, traveled+1));
explored.put(p.hashCode(), p);
if (p.equals(end))
{ solution.add(p);
return cleanSolution(solution, campus, true);
}
}
}
if (frontier.size() == 0)
{ System.out.println("Maze is not solvable");
return null;
}
// set variables for next iteration
CPoint next = frontier.remove(); // best valued move
traveled = next.getTraveled();
current = next.getPoint();
solution.add(current);
}
}
return cleanSolution(solution, campus, true);
} |
720ccad0-1e7f-43d1-909f-e97fcad2c242 | 1 | public Geometry getGeometry() {
if (geometry != null) {
return geometry;
}
render();
GeometryFactory gf = Helper.getGeometryFactory();
Coordinate[] labelCorners = new Coordinate[5];
SVGRect textBox = text.getBBox();
labelCorners[0] = new Coordinate(textBox.getX(), textBox.getY());
labelCorners[1] = new Coordinate(textBox.getX() + textBox.getWidth(),
textBox.getY());
labelCorners[2] = new Coordinate(textBox.getX() + textBox.getWidth(),
textBox.getY() + textBox.getHeight());
labelCorners[3] = new Coordinate(textBox.getX(), textBox.getY()
+ textBox.getHeight());
labelCorners[labelCorners.length-1] = labelCorners[0];
Geometry geo = gf
.createPolygon(gf.createLinearRing(labelCorners), null);
Geometry[] geometries = new Geometry[2];
geometries[0] =geo;
geometries[1] = gf.createPoint(new Coordinate(centerX, centerY));
GeometryCollection gc = new GeometryCollection(geometries, gf);
geometry = gc.convexHull();
geometry = geometry.buffer(text.getSVGContext().getFontSize()/2);
return geometry;
} |
c3734222-c785-4ecf-9d32-0cc37702399d | 8 | private Object[] getDefaultValues (Class type) {
if (!usePrototypes) return null;
if (classToDefaultValues.containsKey(type)) return classToDefaultValues.get(type);
Object object;
try {
object = newInstance(type);
} catch (Exception ex) {
classToDefaultValues.put(type, null);
return null;
}
ObjectMap<String, FieldMetadata> fields = typeToFields.get(type);
if (fields == null) fields = cacheFields(type);
Object[] values = new Object[fields.size];
classToDefaultValues.put(type, values);
int i = 0;
for (FieldMetadata metadata : fields.values()) {
Field field = metadata.field;
try {
values[i++] = field.get(object);
} catch (IllegalAccessException ex) {
throw new JsonException("Error accessing field: " + field.getName() + " (" + type.getName() + ")", ex);
} catch (JsonException ex) {
ex.addTrace(field + " (" + type.getName() + ")");
throw ex;
} catch (RuntimeException runtimeEx) {
JsonException ex = new JsonException(runtimeEx);
ex.addTrace(field + " (" + type.getName() + ")");
throw ex;
}
}
return values;
} |
1f234a2e-225e-4b95-936e-19485f80ede3 | 7 | public void musStart(){
while(true)
{
hand = (hand + 1) % 4;
boolean discardFase = true;
deck = new MusDeck();
deck.shuffle();
for(int i = 0; i < player.length; i++) {
player[i].clearHand();
player[i].receive(deck.deal(4));
}
while(discardFase){
turn = hand;
player[turn % player.length].showHand();
while(player[turn++ % player.length].isMus() && turn < player.length + hand) {
player[turn % player.length].showHand();
}
if(!(turn < player.length + hand))
for(int i = hand; i < player.length + hand; i++) {
System.out.println("Descarte de " + player[i%player.length].getName());
player[i%player.length].receive(deck.discard(player[i%player.length].discard()));
}
else
discardFase = false;
}
System.out.println("Fin de la ronda");
}
} |
2d6eb867-240f-4d88-84a6-173f88fd21b3 | 6 | private void parseChildren(Element e, XMLTag tag) {
NodeList children = e.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node nChild = children.item(i);
if (nChild.getNodeType() == Node.ELEMENT_NODE) {
Element eChild = (Element) nChild;
XMLTag child = new XMLTag(eChild.getNodeName());
child.setParent(tag);
parseElementAttributes(eChild, child);
parseChildren(eChild, child);
tag.addChild(child);
} else if (nChild.getNodeType() == Node.TEXT_NODE) {
String value = nChild.getTextContent();
if (value != null && !value.trim().contentEquals("")) {
tag.setValue(value);
}
} else if (nChild.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) {
PITag child = new PITag(nChild.getNodeName());
child.setValue(nChild.getNodeValue());
child.setParent(tag);
tag.addChild(child);
}
}
} |
a0d6b655-9fa0-486d-b445-6cc8510219c2 | 2 | public void saveLevel(Board board) throws LevelMisconfigurationException {
// the parent folder where the file is created inside
File parentFolder = new File(
CoreConstants.getProperty("editor.basepath"));
/**
* start to validate level configuration
*/
// list with positions of all diamonds
List<Position> diamondPosList = board
.getPositionsOfType(FieldState.DIAMOND);
// list with positions of all goals
List<Position> goalPosList = board.getPositionsOfType(FieldState.GOAL);
// initialize dijkstra algorithm for this board
Dijkstra dijkstra = new Dijkstra(board.getGrid(), Mode.EDITOR);
/**
* check if all diamonds have a connection to any goal
*/
boolean diamondToGoals = checkConnections(dijkstra, diamondPosList,
goalPosList);
/**
* check if all goals have a connection to any diamond
*/
boolean goalToDiamonds = checkConnections(dijkstra, goalPosList,
diamondPosList);
if (!diamondToGoals) {
LOG.error("Error in saving level: diamond without connection to goal!");
throw new LevelMisconfigurationException(
"Fehler: Es gibt einen Diamanten ohne Verbindung zu einem Ziel!");
}
if (!goalToDiamonds) {
LOG.error("Error in saving level: goal without connection to diamond!");
throw new LevelMisconfigurationException(
"Fehler: Es gibt ein Ziel ohne Verbindung zu einem Diamanten!");
}
/**
* prevent to save a modified level with the same uuid again when a
* level is changed in the editor, then it needs a new uuid
*/
board.setUuid(null);
/**
* now save the level to xml, everything should be valid
*/
XmlService.getInstance().saveLevel(board, parentFolder);
} |
219a1c85-e38c-4fa8-90c6-563714f8ee60 | 8 | public boolean addScore(String playerName, int scored) throws CouldNotSaveFileException {
Score score = new Score(scored, playerName);
if (scores.size() < MAX_SCORES || score.compareTo(scores.getLast()) < 0) {
ListIterator<Score> it = scores.listIterator();
while (it.hasNext() && it.next().compareTo(score) <= 0)
;
if (it.hasNext() || (it.hasPrevious() && score.compareTo(scores.getLast()) < 0)) {
it.previous();
}
it.add(score);
if (scores.size() > MAX_SCORES) {
scores.removeLast();
}
saveScores();
return true;
}
return false;
} |
f73a20ab-d8c3-46fc-a8d1-7293bf12d487 | 6 | private static void add(Map<Class<?>, Class<?>> forward,
Map<Class<?>, Class<?>> backward, Class<?> key, Class<?> value) {
forward.put(key, value);
backward.put(value, key);
} |
e041e06c-eb12-4a18-988a-1f6af9cbd79e | 7 | public static Vector<String> parseSquiggleDelimited(String s, boolean ignoreNulls)
{
final Vector<String> V = new Vector<String>();
if ((s == null) || (s.length() == 0))
return V;
int x = s.indexOf('~');
while (x >= 0)
{
final String s2 = s.substring(0, x).trim();
s = s.substring(x + 1).trim();
if ((s2.length() > 0) || (!ignoreNulls))
V.addElement(s2);
x = s.indexOf('~');
}
if ((s.length() > 0) || (!ignoreNulls))
V.addElement(s);
return V;
} |
6b756c77-596a-44dd-8691-dcf9548095a9 | 1 | public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
File file = new File("C:/1.txt");
in = new BufferedReader(new FileReader(file));
String line;
while ((line = in.readLine()) != null) {
int n = Integer.parseInt(line);
System.out.println(fibonacci(n));
}
} |
91479b59-6d8b-478c-b24d-12e0b9250c9c | 4 | private boolean optionsHasAnyOf( OptionSet options, Collection<OptionSpec<?>> specs ) {
for ( OptionSpec<?> each : specs ) {
if ( options.has( each ) )
return true;
}
return false;
} |
43c3cb75-e93f-4735-a914-cf4fa15c8428 | 1 | public List<Object> getContent() {
if (content == null) {
content = new ArrayList<Object>();
}
return this.content;
} |
beba2a1e-4651-41ae-9a60-4dea0e50efef | 5 | @Test
public void testValue() {
System.out.println("value");
Equals<Double> instance = this._instance;
for (int i = 0; i < this._values.length; i++)
for (int j = 0; j < this._values.length; j++) {
boolean expResult = false;
for (Equals<Double> e : this._instance)
expResult |= e.value(this._values[i], this._values[j]);
Boolean result = instance.value(this._values[i], this._values[j]);
String first = (this._values[i] == null ? "null" : this._values[i].toString());
String second = (this._values[j] == null ? "null" : this._values[j].toString());
assertEquals(first + " compared to " + second,
expResult, result);
}
} |
1085345e-985a-4bfe-891e-2e770bcd512b | 4 | public MBeanServerConnection connect() throws MBeanServerConnectionException {
if (vmd == null) {
throw new MBeanServerConnectionException(ReturnCode.ServerNotFound);
}
try {
VirtualMachine vm = VirtualMachine.attach(vmd);
String connectorAddress = getConnectorAddress(vm);
if (connectorAddress == null) {
throw new MBeanServerConnectionException(ReturnCode.ServerHasNoConnectorAddress);
}
JMXServiceURL url = new JMXServiceURL(connectorAddress);
jmxCon = JMXConnectorFactory.connect(url);
mbc = jmxCon.getMBeanServerConnection();
} catch (AttachNotSupportedException ansx) {
LOG.severe(ReturnCode.ServerAttachFailed.getMessage() + ": "
+ ExceptionToStacktraceString.toStacktrace(ansx));
throw new MBeanServerConnectionException(ReturnCode.ServerAttachFailed);
} catch (Exception iox) {
LOG.severe(ReturnCode.ServerCommunicationError.getMessage() + ": "
+ ExceptionToStacktraceString.toStacktrace(iox));
throw new MBeanServerConnectionException(iox, ReturnCode.ServerCommunicationError);
}
return mbc;
} |
737c69cc-ff5c-4fe9-b743-d020c298dac3 | 2 | public void createStatesForConversion(Grammar grammar, Automaton automaton) {
initialize();
StatePlacer sp = new StatePlacer();
String[] variables = grammar.getVariables();
for (int k = 0; k < variables.length; k++) {
String variable = variables[k];
Point point = sp.getPointForState(automaton);
State state = automaton.createState(point);
if (variable.equals(grammar.getStartVariable()))
automaton.setInitialState(state);
state.setLabel(variable);
mapStateToVariable(state, variable);
}
Point pt = sp.getPointForState(automaton);
State finalState = automaton.createState(pt);
automaton.addFinalState(finalState);
mapStateToVariable(finalState, FINAL_STATE);
} |
57002b1f-73eb-47d4-aea1-d2c92672b55d | 9 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final Interval other = (Interval) obj;
if (end == null) {
if (other.end != null)
return false;
} else if (!end.equals(other.end))
return false;
if (start == null) {
if (other.start != null)
return false;
} else if (!start.equals(other.start))
return false;
return true;
} |
d2d2fe32-6dcd-4a34-ad1e-7fb4ebc63c7d | 5 | @Override
public String toString() {
String output = "";
if (isStart)
output += "(START)\t";
else if (isFinal)
output += "(FINAL)\t";
else
output += "\t";
for (String key : transitions.keySet()) {
output += key + "\t";
}
output += "\n" + name + "\t";
for (String key : transitions.keySet()) {
output += "(";
for (State state : transitions.get(key)) {
output += state.name + ",";
}
output = output.substring(0, output.length() - 1); // trims trailing
// comma
output += ")\t";
}
return output + "\n";
} |
ced884d7-ebbf-49a7-ae9f-df9741444f09 | 7 | public static void main(String[] argv)
{
JFrame mainWindow = new JFrame("Übung3");
mainWindow.setLayout(new GridLayout(rows, columns));
mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainWindow.setBackground(Color.white);
mainWindow.setSize(800, 800);
mainWindow.setLocationRelativeTo(null);
GeometricObject [] myObjects = new GeometricObject[rows * columns];
for (int i = 0; i < rows * columns; i++)
{
Color color = new Color(randomGen.nextInt(255), randomGen.nextInt(255), randomGen.nextInt(255));
switch (randomGen.nextInt(5))
{
case 0:
myObjects[i] = new Square(color, Math.random());
break;
case 1:
myObjects[i] = new Circle(color, Math.random());
break;
case 2:
myObjects[i] = new Triangle(color, Math.random());
break;
case 3:
myObjects[i] = new PacMan(color, Math.random());
break;
case 4:
myObjects[i] = new MySpecialShape(color, Math.random());
break;
default:
}
}
for (int i = 0; i < rows * columns; i++)
{
mainWindow.add(myObjects[i]);
}
mainWindow.setVisible(true);
} |
42e11d32-5597-488b-ae9a-fd2e2c316562 | 7 | private Instances[] computeInfoGain(Instances instances, double defInfo, Antd antd){
Instances data = new Instances(instances);
/* Split the data into bags.
The information gain of each bag is also calculated in this procedure */
Instances[] splitData = antd.splitData(data, defInfo);
Instances[] coveredData = new Instances[2];
/* Get the bag of data to be used for next antecedents */
Instances tmp1 = new Instances(data, 0);
Instances tmp2 = new Instances(data, 0);
if(splitData == null)
return null;
for(int x=0; x < (splitData.length-1); x++){
if(x == ((int)antd.getAttrValue()))
tmp1 = splitData[x];
else{
for(int y=0; y < splitData[x].numInstances(); y++)
tmp2.add(splitData[x].instance(y));
}
}
if(antd.getAttr().isNominal()){ // Nominal attributes
if(((NominalAntd)antd).isIn()){ // Inclusive expression
coveredData[0] = new Instances(tmp1);
coveredData[1] = new Instances(tmp2);
}
else{ // Exclusive expression
coveredData[0] = new Instances(tmp2);
coveredData[1] = new Instances(tmp1);
}
}
else{ // Numeric attributes
coveredData[0] = new Instances(tmp1);
coveredData[1] = new Instances(tmp2);
}
/* Add data with missing value */
for(int z=0; z<splitData[splitData.length-1].numInstances(); z++)
coveredData[1].add(splitData[splitData.length-1].instance(z));
return coveredData;
} |
633eef44-ade4-45c4-8f5f-c19970d30213 | 8 | public double calculate(HttpServletRequest request) {
int shape = Integer.parseInt(request.getParameter("s"));
// double result;
switch (shape) {
case 0:
calc = new RectangleCalculator();
return calc.calcArea(parseValue(request.getParameter("length")), parseValue(request.getParameter("width")));
case 1:
calc = new CircleCalculator();
return calc.calcArea(parseValue(request.getParameter("radius")), parseValue(request.getParameter("radius")));
case 2:
calc = new TriangleCalculator();
return calc.calcArea(parseValue(request.getParameter("base")), parseValue(request.getParameter("height")));
case 3:
calc = new TriangleCalculator();
// if(request.getParameter("sideC") == null || parseValue(request.getParameter("sideC")) == 0) {
// return calc.calcHypotenuse(parseValue(request.getParameter("sideA")), parseValue(request.getParameter("sideC")));
// }
// TriangleCalculator tri = new TriangleCalculator();
/*
* This makes no sense why I have to do it this way
* ------------------------------------------------
* Why do I have to use static methods?
* Why does my calc object not have access to the non-implemented methods?
*/
if(parseValue(request.getParameter("sideC")) == 0 || request.getParameter("sideC").equals("")) {
return TriangleCalculator.calcHypotenuse(parseValue(request.getParameter("sideA")), parseValue(request.getParameter("sideB")));
}
if (parseValue(request.getParameter("sideB")) == 0) {
return TriangleCalculator.calcLegs(parseValue(request.getParameter("sideA")), parseValue(request.getParameter("sideC")));
}
if (parseValue(request.getParameter("sideA")) == 0) {
return TriangleCalculator.calcLegs(parseValue(request.getParameter("sideB")), parseValue(request.getParameter("sideC")));
}
default:
return 0;
}
} |
89de9f24-3b72-4600-8084-87e37f29df96 | 4 | public static int[] factorsOf(int number) {
if (number < 0) {
throw new IllegalArgumentException("Error: int cannot be < 0!");
}
int half = Math.round(number / 2);
ArrayList<Integer> factorsList = new ArrayList<Integer>();
for (int j = 1; j <= half; j++) {
if (number % j == 0) {
factorsList.add(j);
}
}
factorsList.add(number);
int[] factors = new int[factorsList.size()];
for (int k = 0; k < factorsList.size(); k++)
factors[k] = factorsList.get(k);
return factors;
} |
9c2b35af-81e0-4ef3-9e15-5219562031d3 | 2 | public static void main(String args[]) {
TowerDefenseGame game = new TowerDefenseGame();
game.initConnection();
while (!game.checkInitalBridge()) {
try {
sleep(delay);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Try Create");
}
} |
0cbaa4bd-fd90-4454-877e-e2fa066f65fc | 8 | @Override
public List<TrainingDataDTO> getTraningDataByCrisisAndAttribute(int crisisID,
int modelFamilyID,
int fromRecord,
int limit,
String sortColumn,
String sortDirection) {
List<TrainingDataDTO> trainingDataList = new ArrayList<TrainingDataDTO>();
String orderSQLPart = "";
if (sortColumn != null && !sortColumn.isEmpty()){
if (sortDirection != null && !sortDirection.isEmpty()) {
if ("ASC".equals(sortDirection)) {
sortDirection = "ASC";
} else {
sortDirection = "DESC";
}
} else {
sortDirection = "ASC";
}
orderSQLPart += " ORDER BY " + sortColumn + " " + sortDirection + " ";
}
String sql = " SELECT lbl.nominalLabelID, lbl.name labelName, d.data tweetJSON, u.userID, u.name labelerName, dnl.timestamp "
+ " FROM document_nominal_label dnl "
+ " JOIN nominal_label lbl on lbl.nominalLabelID=dnl.nominalLabelID "
+ " JOIN model_family mf on mf.nominalAttributeID=lbl.nominalAttributeID "
//+ " JOIN model m on m.modelFamilyID= mf.modelFamilyID "
+ " JOIN document d on d.documentID = dnl.documentID "
+ " JOIN task_answer ta on ta.documentID = d.documentID "
+ " JOIN users u on u.userID = ta.userID "
+ " WHERE mf.modelFamilyID = :modelFamilyID AND d.crisisID = :crisisID " + orderSQLPart
+ " LIMIT :fromRecord, :limit";
String sqlCount = " SELECT count(*) "
+ " FROM document_nominal_label dnl "
+ " JOIN nominal_label lbl on lbl.nominalLabelID=dnl.nominalLabelID "
+ " JOIN model_family mf on mf.nominalAttributeID=lbl.nominalAttributeID "
//+ " JOIN model m on m.modelFamilyID= mf.modelFamilyID "
+ " JOIN document d on d.documentID = dnl.documentID "
+ " JOIN task_answer ta on ta.documentID = d.documentID "
+ " JOIN users u on u.userID = ta.userID "
+ " WHERE mf.modelFamilyID = :modelFamilyID AND d.crisisID = :crisisID ";
try {
Integer totalRows;
Query queryCount = em.createNativeQuery(sqlCount);
queryCount.setParameter("crisisID", crisisID);
queryCount.setParameter("modelFamilyID", modelFamilyID);
Object res = queryCount.getSingleResult();
totalRows = Integer.parseInt(res.toString());
if (totalRows > 0){
Query query = em.createNativeQuery(sql);
query.setParameter("crisisID", crisisID);
query.setParameter("modelFamilyID", modelFamilyID);
query.setParameter("fromRecord", fromRecord);
query.setParameter("limit", limit);
List<Object[]> rows = query.getResultList();
TrainingDataDTO trainingDataRow;
for (Object[] row : rows) {
trainingDataRow = new TrainingDataDTO();
trainingDataRow.setLabelID(((Integer) row[0]).intValue());
trainingDataRow.setLabelName((String) row[1]);
trainingDataRow.setTweetJSON((String) row[2]);
trainingDataRow.setLabelerID(((Integer) row[3]).intValue());
trainingDataRow.setLabelerName((String) row[4]);
trainingDataRow.setLabeledTime(((Date) row[5]));
trainingDataRow.setTotalRows(totalRows);
trainingDataList.add(trainingDataRow);
}
}
return trainingDataList;
} catch (NoResultException e) {
return null;
}
} |
a1a4573f-e104-439f-a9bb-806324af5417 | 5 | public static void runCPP(final String s2) {
Thread t = new Thread(){
public void run() {
String s = new String("\n#include <iostream>\n" +
"using namespace std;\n" +
"int main() {\n" +
s2 + "\n" +
"return 0; \n}");
ArrayList<String> data = new ArrayList<String>();
data.add(s);
IOTools.writeToFile(new File("CMain.cpp"), data);
if (s2.contains("Runtime")) {
CommandHandler.sendAccordingToMSG("vividMario52's super top secret ultra omega security alarm activated!");
CommandHandler.sendAccordingToMSG("brring brring brring");
return;
}
try {
//CommandHandler.sendAccordingToMSG("Starting Program in seperate thread...");
if (runProcess("g++ -c CMain.cpp") == 1) {
return;
}
if (runProcess("g++ CMain.o") == 1) {
return;
}
if (runProcess("./a.out") == 1) {
return;
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
t.start();
threads.add(t);
} |
022a7bd7-04bc-4772-a565-c189a9740749 | 4 | public float[][] GenerateFurniHeightMap()
{
float[][] FurniHeightMap = new float[this.GrabModel().MapSizeX][this.GrabModel().MapSizeY];
for(int x = 0; x < this.GrabModel().MapSizeX; x++) //Loopception courtesy of Cobe & Cecer
{
for(int y = 0; y < this.GrabModel().MapSizeY; y++)
{
if(FurniCollisionMap[x][y] == 0)
{
FurniHeightMap[x][y] = (float)this.GrabModel().SquareHeight[x][y];
}
else
{
for(FloorItem Item : FloorItems.values())
{
FurniHeightMap[x][y] = Item.Height;
}
}
}
}
return FurniHeightMap;
} |
07e474cd-892b-414e-85c4-8cf70de0ac46 | 2 | private AnimationType generateAnimation(String animation) {
if (animation.contains("MoveCardAnimation")) {
if (animation.contains(":")) {
// has parameters pass them to the constructor
return new MoveCardAnimation(animation.split(":")[1]);
} else {
return new MoveCardAnimation();
}
}
return null;
} |
7d9f2f4e-2168-4064-84d3-1f0d8e4e2bae | 0 | public BasicFileFilter() {} |
05ccac7c-8470-413e-a1ef-9acf4ca1de01 | 6 | @Override
public void process() {
session.log("Loading class for client: \""+clientClassName+"\"");
Class clnMain;
try {
clnMain = Class.forName(clientClassName);
}catch(ClassNotFoundException clnfe){
session.log("Unable to load class\n"+clnfe.toString());
return;
}
Object o=null;
try {
o = clnMain.newInstance();
}catch(InstantiationException iex){
session.log("Unable to instantiate class\n"+iex.toString());
return;
}catch(IllegalAccessException iax){
session.log("Unable to instantiate class\n"+iax.toString());
}
clientObject = (RsRunnable)o;
if(supplyClientIO){
SimClient simClient = new SimClient(session);
try{
PipedOutputStream clnOut = new PipedOutputStream();
PipedInputStream srvIn = new PipedInputStream(clnOut);
PipedOutputStream srvOut = new PipedOutputStream();
PipedInputStream clnIn = new PipedInputStream(srvOut);
simClient.setInputOutputStreams(srvIn, srvOut);
clientObject.setInputOutputStreams(clnIn, clnOut);
}catch (IOException eio){
session.log("Serious error, unable to create client/server IO");
return;
}
session.log("Adding SimClient and starting its connection thread");
session.addSessionElementsToClient(simClient);
(new Thread(simClient)).start();
}
if(supplyClientLogging){
clientObject.setLogger(session);
}
session.log("Launching thread for client: \""+clientClassName+"\"");
(new Thread(this)).start();
} |
fb0e7253-bfcd-4eb9-b1e5-a669400daa94 | 3 | public static double toRadians(double x)
{
if (Double.isInfinite(x) || x == 0.0) { // Matches +/- 0.0; return correct sign
return x;
}
// These are PI/180 split into high and low order bits
final double facta = 0.01745329052209854;
final double factb = 1.997844754509471E-9;
double xa = doubleHighPart(x);
double xb = x - xa;
double result = xb * factb + xb * facta + xa * factb + xa * facta;
if (result == 0) {
result = result * x; // ensure correct sign if calculation underflows
}
return result;
} |
a78f70d5-059b-438b-88d8-5e5e4b05e471 | 3 | private static boolean tryToOccupyUrinalAndSurvive() {
int urinalToOccupy = askForNumberBetween( "Which Urinal shall be occupied?", minUrinals, bathroom.urinalCount() );
UrinalStatus status = bathroom.occupyUrinalVO( urinalToOccupy-1 );
switch( status ) {
case FREE_SAVE:
print( "Aaaaah. That's better..." );
return true;
case TRAPPED:
println( "BANG! This toilet was trapped. You should have kept your distance." );
return false;
case OCCUPIED:
print( "Dude! Someone's already peeing here. Try another one." );
return true;
default:
print( "Something's strange here..." );
return false;
}
} |
13166554-ddf3-47ab-9347-4ec0b53e7d26 | 6 | public void toggleAction(Action a, boolean is) {
if (a == null) return ;
if (! a.actor.inWorld()) {
I.complain(a+" TOGGLED BY DEFUNCT ACTOR: "+a.actor) ;
}
final Target t = a.target() ;
List <Action> forT = actions.get(t) ;
if (is) {
if (forT == null) actions.put(t, forT = new List <Action> ()) ;
forT.include(a) ;
}
else if (forT != null) {
forT.remove(a) ;
if (forT.size() == 0) actions.remove(t) ;
}
} |
d718b857-45b3-4ffa-90a3-647d41316a68 | 1 | public boolean checkAccess(Administrador admin){
try {
PreparedStatement ps =
this.mycon.prepareStatement("SELECT * FROM Administradores WHERE userName=? AND passwd=?");
ps.setString(1, admin.getNombre());
ps.setString(2, admin.getPassword());
ResultSet rs = ps.executeQuery();
return rs.next();
} catch (SQLException ex) {
Logger.getLogger(AdministradorCRUD.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
} |
e0b029ae-ae41-41a0-9158-fa5144664d93 | 5 | public int getRealWidth() {
int c = 0;
for (int x = 1; x < width; x++) {
for (int y = 0; y < height; y++) {
int col = pixels[x + y * width];
if (col == -1 || col == 0xffff00ff) c++;
}
if (c == height) return x;
c = 0;
}
return width;
} |
4809c987-1675-48ee-be1a-9189675457d8 | 0 | public void setSysMessage(String sysMessage) {
this.sysMessage = sysMessage;
} |
fe81b501-bfc5-4448-ab69-202944019868 | 2 | public boolean overTwoTimes(int[] counts) {
for (int i = 0; i < counts.length; i++) {
if (counts[i] > 1)
return false;
}
return true;
} |
342ac369-892d-432a-a58f-ad72382c87ea | 2 | private static double getHighThreshold(ImageProcessor gradient, double percentNotEdges){
gradient.setHistogramSize(64);
int[] histogram = gradient.getHistogram();
long cumulative = 0;
long totalNotEdges = Math.round(gradient.getHeight()*gradient.getWidth()*percentNotEdges);
int buckets = 0;
for(; buckets < 64 && cumulative < totalNotEdges; buckets++){
cumulative += histogram[buckets];
}
return buckets/64.0;
} |
1b1ddfa7-ad40-4904-9741-1e16c46a1cb2 | 3 | public boolean load(String audiofile) {
try {
setFilename(audiofile);
sample = AudioSystem.getAudioInputStream(getURL(filename));
clip.open(sample);
return true;
} catch (IOException e) {
return false;
} catch (UnsupportedAudioFileException e) {
return false;
} catch (LineUnavailableException e) {
return false;
}
} |
8e0e8116-d0fe-43ee-b4aa-f8bacc46860d | 0 | private void dehighlight() {
pane.tablePanel.dehighlight();
pane.grammarTable.dehighlight();
} |
3fd9f93f-5d69-4c47-8257-2f99573376e9 | 6 | @Override
public synchronized void advance(double smpSecondsElapsed,double seqSecondsElapsed){
int chan=output.length;
for(int i=0;i<chan;i++) output[i]=0;
boolean stop=terminate;
Node n=head.next;
while(n.next!=null){
double[] signal=n.sound.getSignal(smpSecondsElapsed,seqSecondsElapsed);
if(signal==null){
n.next.prev=n.prev;
n=n.prev.next=n.next;
childCount--;
}else{
stop=false;
int j=0;
for(int i=0;i<chan;i++){
output[i]+=signal[j];
if(++j==signal.length) j=0;
}
n=n.next;
}
}
if(stop) stop();
} |
009cb813-3e45-45b0-9aa9-03f4086b7c13 | 3 | void updateInOut(FlowBlock successor, SuccessorInfo succInfo) {
/*
* First get the gen/kill sets of all jumps to successor and calculate
* the intersection.
*/
SlotSet kills = succInfo.kill;
VariableSet gens = succInfo.gen;
/*
* Merge the locals used in successing block with those written by this
* blocks.
*/
successor.in.merge(gens);
/*
* The ins of the successor that are not killed (i.e. unconditionally
* overwritten) by this block are new ins for this block.
*/
SlotSet newIn = (SlotSet) successor.in.clone();
newIn.removeAll(kills);
/*
* The gen/kill sets must be updated for every jump in the other block
*/
Iterator i = successor.successors.values().iterator();
while (i.hasNext()) {
SuccessorInfo succSuccInfo = (SuccessorInfo) i.next();
succSuccInfo.gen.mergeGenKill(gens, succSuccInfo.kill);
if (successor != this)
succSuccInfo.kill.mergeKill(kills);
}
this.in.addAll(newIn);
this.gen.addAll(successor.gen);
if ((GlobalOptions.debuggingFlags & GlobalOptions.DEBUG_INOUT) != 0) {
GlobalOptions.err.println("UpdateInOut: gens : " + gens);
GlobalOptions.err.println(" kills: " + kills);
GlobalOptions.err.println(" s.in : " + successor.in);
GlobalOptions.err.println(" in : " + in);
}
} |
d89fa25c-8466-44f3-8976-6cec57cb9270 | 8 | @Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
RelationshipFamilyEntity that = (RelationshipFamilyEntity) o;
if (relationshipId != that.relationshipId) return false;
if (familyId1 != null ? !familyId1.equals(that.familyId1) : that.familyId1 != null) return false;
if (familyId2 != null ? !familyId2.equals(that.familyId2) : that.familyId2 != null) return false;
return true;
} |
806ac051-437d-46d8-b485-15c475d961cb | 9 | private static void printLCS(int[][] lcs, char[] x, char[] y, int i, int j) {
if(i >0 && j >0 && x[i-1]==y[j-1] ){
printLCS(lcs,x,y,i-1,j-1);
//Prints only if X == Y...
System.out.print(x[i-1]);
}else if(j>0 && (i==0 || lcs[i][j-1]>=lcs[i-1][j])){
printLCS(lcs,x,y,i,j-1);
}else if(i>0 && (j==0 || lcs[i][j-1] < lcs[i-1][j])){
printLCS(lcs,x,y,i-1,j);
} else{ }
} |
f3bd5943-821c-4da7-8db9-327d9d51b6d6 | 4 | private static void createDirectory(FileSystem fileSystem, String path) throws TestFailedException {
try {
fileSystem.createDirectory(path);
if (!fileSystem.pathExists(path))
throw new TestFailedException("I created the directory " + path + ", but pathExists says it does not exist");
} catch (PathNotFoundException e) {
throw new TestFailedException("createDirectory(" + path + ")", e);
} catch (DestinationAlreadyExistsException e) {
throw new TestFailedException("Should not occur", e);
} catch (AccessDeniedException e) {
throw new TestFailedException(e);
}
} |
2b0839e6-e8d7-49d7-abc9-57c2fb77998f | 5 | public void addNode(int value, int leftValue, int rightValue) {
if (leftValue == -1 && rightValue == -1) {
return;
}
Node node = this.getNodeByValue(value);
if (node == null) {
System.out.println("Error, no node with value:" + value);
return;
}
if (leftValue != -1) {
node.leftChild = new Node(leftValue, node);
}
if (rightValue != -1) {
node.rightChild = new Node(rightValue, node);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.