method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
0f173b28-31cc-47ae-bffa-5f9f2aa6212f
4
public static void main(String[] args) { Scanner inputScanner = null; try { inputScanner = new Scanner(new File(args[0])); } catch (Exception e) { System.err.println("Invalid file input"); } int input; int count; int count2; int count3; while (inputScanner.hasNextLine()) { count = 1; count2 = 0; count3 = 0; input = Integer.parseInt(inputScanner.nextLine()); if (input == 1) { System.out.println(count); } for (int x = 1; x < input; x++) { count3 = count; count += count2; count2 = count3; } System.out.println(count); } }
fe08001d-f2af-49ce-90c5-45dc87458d3b
3
String[] getMOTD() { try { File file = new File("MOTD.txt"); if(!file.exists()){ file.createNewFile(); } BufferedReader r = new BufferedReader(new FileReader(file)); ArrayList < String > temparray = new ArrayList < String > (); String s = null; while ((s = r.readLine()) != null) { temparray.add(s); } Object[] ret = temparray.toArray(); String[] toret = Arrays.copyOf(ret, ret.length, String[].class); return toret; } catch (IOException e) { e.printStackTrace(); } return null; }
1cbcfe1f-984c-4397-9dc7-90aa45915bcb
4
public boolean matchesSub(Identifier ident, String subident) { String prefix = ident.getFullName(); if (prefix.length() > 0) prefix += "."; if (subident != null) prefix += subident; if (firstStar == -1 || firstStar >= prefix.length()) return wildcard.startsWith(prefix); return prefix.startsWith(wildcard.substring(0, firstStar)); }
6e68a596-71a5-4121-8f9c-82499d373a03
9
public void updateProcess(int NEW_STATE) { long timePassed = SystemClock.getTime()-this.timeOfLastEvent; if (NEW_STATE == CPU_QUEUE) { Statistics.processesPlacedInCpuQueue(); } else if (NEW_STATE == IO_QUEUE) { Statistics.processesPlacedInIOQueue(); } else if (NEW_STATE == FINISHED) { Statistics.processCompleted(); Statistics.processesTotalTimeInSystem(SystemClock.getTime()-this.timeAddedToSystem); } if (PREV_STATE == MEMORY_QUEUE) { this.timeAddedToSystem = SystemClock.getTime(); this.timeSpentInMemoryQueue += timePassed; Statistics.processMemoryWait(timePassed); Statistics.processAccepted(); } else if (PREV_STATE == CPU_ACTIVE) { this.timeSpentInCpu += timePassed; Statistics.cpuActiveTime(timePassed); this.timeToNextIoOperation -= timePassed; this.cpuTimeNeeded -= timePassed; if (timeToNextIoOperation == 0) { this.timeToNextIoOperation = this.generateTimeToNextIoOperation(); } } else if (NEW_STATE == CPU_ACTIVE) { this.timeSpentInCPUQueue += timePassed; Statistics.processCPUWait(timePassed); } else if (PREV_STATE == IO_QUEUE) { this.timeSpentInIoQueue += timePassed; Statistics.processIOWait(timePassed); } else if (PREV_STATE == IO_ACTIVE) { this.timeSpentInIo += timePassed; Statistics.ioActiveTime(timePassed); } PREV_STATE = NEW_STATE; this.timeOfLastEvent = SystemClock.getTime(); }
8e4b063e-aac4-4ad6-8a0b-5fe4b0b22a05
5
private String determineChomp (String text) { String tail = text.substring(text.length() - 2, text.length() - 1); while (tail.length() < 2) tail = " " + tail; char ceh = tail.charAt(tail.length() - 1); char ceh2 = tail.charAt(tail.length() - 2); return ceh == '\n' || ceh == '\u0085' ? ceh2 == '\n' || ceh2 == '\u0085' ? "+" : "" : "-"; }
ae2b4f2f-8a0e-42c0-a497-eccb8ec99cb9
7
public boolean checkEndConditions(){ //the return value boolean retVal = false; try{ //the number of each piece left int whitesGone = 0 , bluesGone = 0; //the board to work with Board temp = theFacade.stateOfBoard(); //go through all the spots on the board for( int i=1; i<temp.sizeOf(); i++ ){ //if there is a piece there if( temp.occupied( i ) ){ //if its a blue piece there if( (temp.getPieceAt( i )).getColor() == Color.blue ){ // increment number of blues bluesGone++; //if the piece is white }else if( (temp.getPieceAt( i )).getColor() == Color.white ){ //increment number of whites whitesGone++; } } }//end of for loop //if either of the number are 0 if( whitesGone == 0 || bluesGone == 0 ){ retVal = true; } }catch( Exception e ){ System.err.println( e.getMessage() ); } return retVal; }//checkEndConditions
b670497f-8bf1-4b40-960b-184188d55356
4
public double perimeter() throws TypeOverflowException { double p = 0; try { for (Iterator<Line> it = lineIterator(); it.hasNext(); ) { p += it.next().distance(); if (Double.isInfinite(p) || Double.isNaN(p)) throw new TypeOverflowException(); } } catch(OverflowException e) { throw new TypeOverflowException(); } return p; }
e6649d6a-1acb-4d03-8cfd-2a3d9daa2d71
9
private void affichageErreursDiffuseur(List<Error> erreursDiffuseur) { for (Error e : erreursDiffuseur) { switch (e) { case raisonSocialeVide: this.labelErreurRaisonSocialeDiffuseur.setText("Veuillez saisir une raison sociale"); break; case telephoneVide: this.labelErreurTelephoneDiffuseur.setText("Veuillez saisir un numéro de telephone"); break; case telephoneInvalide: this.labelErreurTelephoneDiffuseur.setText("Veuillez saisir un numéro de telephone valide"); break; case emailVide: this.labelErreurEmailDiffuseur.setText("Veuillez saisir une adresse email"); break; case emailInvalide: this.labelErreurEmailDiffuseur.setText("Veuillez saisir une adresse email valide"); break; case adresseVide: this.labelErreurAdresseDiffuseur.setText("Veuillez saisir une adresse"); break; case siretVide: this.labelErreurSiretDiffuseur.setText("Veuillez saisir un numéro de siret"); break; case siretInvalide: this.labelErreurSiretDiffuseur.setText("Veuillez saisir un numéro de siret valide"); break; } } }
215f53b3-4f3f-4b48-9620-fdcb405dfc68
9
public void init(File param){ isInialize=true; try { configFile = FileConfig.deserializeXMLToObject(param); } catch (FileNotFoundException e1) {e1.printStackTrace();} /* * Download SVM */ try { File f = new File(configFile.getBinSVM()); if(f.exists()){ FileInputStream fis = new FileInputStream(f); ObjectInputStream ois = new ObjectInputStream(fis); svm = (SMOSVM<double[]>)ois.readObject(); ois.close(); } } catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} catch (ClassNotFoundException e) {e.printStackTrace();} /* * Download Dico */ dicoCenters = new ArrayList<double[][]>(); dicoSigma = new ArrayList<double[]>(); for(String codebook : configFile.getDicoHsv()){ //visual codebook ObjectInputStream oin; try { oin = new ObjectInputStream(new FileInputStream(codebook)); dicoCenters.add((double[][]) oin.readObject()); dicoSigma.add((double[]) oin.readObject()); oin.close(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
6b670810-ac06-458d-9ef8-2c2cf45aade8
1
public boolean connect() { try { connectionSocket = new DatagramSocket(); inetAddress = InetAddress.getByName(ip); } catch (Exception e) { e.printStackTrace(); return false; } return true; }
0fab2a5f-2018-4fdb-a0d5-fa6b0cbf4454
1
* @throws UnknownHostException if cyc server host not found on the network * @throws IOException if a data communication error occurs * @throws CycApiException if the api request results in a cyc server error */ public void converseVoid(final Object command) throws UnknownHostException, IOException, CycApiException { Object[] response = {null, null}; response = converse(command); if (response[0].equals(Boolean.FALSE)) { throw new ConverseException(command, response); } }
0a12d96d-29cf-4765-82be-5ea0a6c88822
2
public int lastLineNumber(){ int lineNum = parse.getLastLineNumber(); if (lineNum <= -1) return -1; // Nothing has been read yet if (lineNum == 1) return -1; // only labels have been read return lineNum - 1; // adjust line number to account for the label line }
67138f0b-5630-49bb-8647-f9ba7ce12764
2
@Override public void paintComponent(Graphics graphics) { // Controls when canvas needs to be drawn onto. if (this.startDraw) { // Get the reference of graphics ovject and pass it to screengc. Graphics screengc = graphics; // Get the graphics instead from the bufferImage. graphics = this.bufferImage.getGraphics(); // Sets the drawing area of the bufferImage. graphics.fillRect(0, 0, GlobalSettingsManager.CANVAS_WIDTH, GlobalSettingsManager.CANVAS_HEIGHT); // Iterates the list of Drawables then draw it on the bufferImage. for (Drawable aShape : this.listOfDrawables) { aShape.drawShape(graphics); } // Draws the buffer image onto the JPanel. screengc.drawImage(this.bufferImage, 0, 0, null); // Afterwards dispose all graphic contents to save memory. graphics.dispose(); } }
cb3269d8-80e7-4bf6-b7ef-b2c601921c90
6
@Override public String toString() { StringBuffer sb = new StringBuffer(); sb.append("<td valign='top'>"); sb.append("Event created by: ").append(getCreator()+"<br />"); sb.append("Date: ").append(new Date(getDatetimemillis())+"<br />"); sb.append("Position: ").append(getLatitude()+","+getLongitude()+"<br />"); if(getClassName().equals("Event")){ if(emotionList.size()>0){ sb.append("Emotions connected to this event: "); for (Emotion emo : emotionList) { sb.append("Emotion: ").append(emo.getEmotionType().getName()+"<br />"); } } if(eventItems.size()>0){ sb.append("The event contains : ").append(eventItems.size()+" items<br />"); for (EventItem eit : eventItems) { sb.append(eit.toString()); } } }else if(getClassName().equals("MoodEvent")){ sb.append("Mood: Valence:"+getValence()+", arousal:"+getArousal()); } sb.append("</td>"); return sb.toString(); }
2e86822f-ce21-408b-8cb7-a9e7e38e8799
9
@Override public void checkForMutations() { // Convenience variables. AbstractAction replicateAction = ((AbstractAction)replicationResult.getReplicate()); Collection<ICondition> original = action.getConditions(); Collection<ICondition> replicate = replicateAction.getConditions(); // Look for addition and/or replacement mutations. if (original.size() == replicate.size() - 1) { incrementMutationCount(MutationType.ADDITION); // Ensure that we saw the appropriate number of addition mutations. assertThatMutationWasSeenOnce(MutationType.ADDITION); // Also look for replacement mutations by checking to see if all of the original actions are in the replicate. // If this is the case then there were no replacements. // We can't generalize this because an addition may have also occurred. if (!replicate.containsAll(original)) { incrementMutationCount(MutationType.REPLACEMENT); // Ensure that we saw the appropriate number of replacement mutations. assertThatMutationWasSeenOnce(MutationType.REPLACEMENT); } } // Look for deletion and/or replacement mutations. if (original.size() == replicate.size() + 1) { incrementMutationCount(MutationType.DELETION); // Ensure that we saw the appropriate number of deletion mutations. assertThatMutationWasSeenOnce(MutationType.DELETION); // Also look for replacement mutations by checking to see if all of the replicate actions are in the original. // If this is the case then there were no replacements. // We can't generalize this because an addition may have also occurred. if (!original.containsAll(replicate)) { incrementMutationCount(MutationType.REPLACEMENT); // Ensure that we saw the appropriate number of replacement mutations. assertThatMutationWasSeenOnce(MutationType.REPLACEMENT); } } // Look for replacements when the original is the same size as the replicate. if (replicate.size() == original.size() && !original.containsAll(replicate)) { incrementMutationCount(MutationType.REPLACEMENT); // Ensure that we saw the appropriate number of replacement mutations. assertThatMutationWasSeenOnce(MutationType.REPLACEMENT); } // Check for any differences in mutation rates. If we see a difference, that means the mutation rate changed. for (MutationType type : MutationType.values()) { if (action.getMutationProbabilitySet().getProbability(type) != replicateAction.getMutationProbabilitySet().getProbability(type)) { incrementMutationCount(MutationType.MUTATION_RATE_CHANGE); break; } } // If the collections are grossly different then some unexpected mutation has occurred. if (Math.abs(original.size() - replicate.size()) > 1) { fail("Original condition collection and replicate are greatly different. Original size: " + original.size() +"; replicate size: " + replicate.size()); } }
3c4c90aa-0bde-4759-96c0-a2b5b5b5750f
8
public Image attackImage(int i) { Image temp = null; switch(i) { case 1: temp = new ImageIcon("src/images/north_attack.png").getImage(); break; case 2: temp = new ImageIcon("src/images/north_east_attack.png").getImage(); break; case 3: temp = new ImageIcon("src/images/east_attack.png").getImage(); break; case 4: temp = new ImageIcon("src/images/south_east_attack.png").getImage(); break; case 5: temp = new ImageIcon("src/images/south_attack.png").getImage(); break; case 6: temp = new ImageIcon("src/images/south_west_attack.png").getImage(); break; case 7: temp = new ImageIcon("src/images/west_attack.png").getImage(); break; case 8: temp = new ImageIcon("src/images/north_west_attack.png").getImage(); break; default: break; } return temp; }
a32f01b2-4411-4019-8957-c30c76993a0f
6
public void FixCSV(String filePath, boolean isFixHeader) throws FileNotFoundException, IOException{ FileManager fm = new FileManager(); fm.copy(filePath, "c:/temp",true); File theFile = new File("c:/temp"); FileReader readerFile = new FileReader(theFile); BufferedReader bufReadFile = new BufferedReader(readerFile); System.out.println("Hasil Baca File Membaca per baris"); String readByte = null; FileWriter writer = new FileWriter(filePath ); int pencacah = 0; while ((readByte = bufReadFile.readLine()) != null) { pencacah++; String[] data = readByte.split(","); for (int i=0;i<data.length;i++){ if (isFixHeader && pencacah==1){ if (data[i].substring(data[i].length()-1, data[i].length()).equals("\"")){ if (i==0){ data[i]= data[i].substring(2, data[i].length()-1); } else { data[i]= data[i].substring(1, data[i].length()-1); } } } writer.append(data[i]); writer.append(','); } writer.append('\n'); } writer.flush(); writer.close(); System.out.println("Jumlah Row File CSV : " + pencacah); System.out.println("Selesai"); }
272fd746-7739-41f4-8f78-5c8c37b2de3c
9
public SchemeObject readSymbol(){ StringBuilder buffer = new StringBuilder(); int c = getc(); while(isInitial(c) || Character.isDigit(c) || c == '+' || c == '-' || c == '.' || c == '/' || c == '_' || c == '&'){ buffer.append((char)c); c = getc(); } if(isDelimiter(c)){ ungetc(c); return SchemeObject.makeSymbol(buffer.toString()); }else{ throw new SchemeException("Symbol not followed by delimiter"); } }
d99083df-60f0-4b74-884d-40d50f025802
9
public int compareTo( Object obj ) { if( obj == null ) { return( 1 ); } else if( obj instanceof GenKbSecFormByUJEEServletIdxKey ) { GenKbSecFormByUJEEServletIdxKey rhs = (GenKbSecFormByUJEEServletIdxKey)obj; if( getRequiredSecAppId() < rhs.getRequiredSecAppId() ) { return( -1 ); } else if( getRequiredSecAppId() > rhs.getRequiredSecAppId() ) { return( 1 ); } { int cmp = getRequiredJEEServletMapName().compareTo( rhs.getRequiredJEEServletMapName() ); if( cmp != 0 ) { return( cmp ); } } return( 0 ); } else if( obj instanceof GenKbSecFormBuff ) { GenKbSecFormBuff rhs = (GenKbSecFormBuff)obj; if( getRequiredSecAppId() < rhs.getRequiredSecAppId() ) { return( -1 ); } else if( getRequiredSecAppId() > rhs.getRequiredSecAppId() ) { return( 1 ); } { int cmp = getRequiredJEEServletMapName().compareTo( rhs.getRequiredJEEServletMapName() ); if( cmp != 0 ) { return( cmp ); } } return( 0 ); } else { throw CFLib.getDefaultExceptionFactory().newUnsupportedClassException( getClass(), "compareTo", "obj", obj, null ); } }
630b0574-565f-4ef3-bdb8-4100a3304f80
1
public MediaUrlDao() { // create a database connection try { con = DriverManager. getConnection("jdbc:h2:./database/twitterKeyWordSearch.h2"); tableCheckAndCreate(); } catch (SQLException e) { // TODO 自動生成された catch ブロック e.printStackTrace(); } }
b15fbab4-0858-4117-934a-96ed9bbf98de
4
public static byte pedir_q_cuenta(){ byte aux=0; do{ try{ System.out.println("1. Ingreso en Cuenta Corriente"); System.out.println("2. Ingreso en Cuenta Ahorro"); System.out.print("OP => "); BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in)); aux=Byte.parseByte(stdin.readLine()); }catch(NumberFormatException e){ System.out.println(e+"Valores numericos enteros"); } catch (IOException e) { e.printStackTrace(); } }while(aux!=1 && aux!=2); return aux; }
bb93e631-7fc2-45e4-ba77-48c6f42de6c2
4
@Override public boolean execute(Player player) { if (!player.getInventory().hasItem("beamer")) { GameEngine.gui.println("You can not teleport without the beamer."); return false; } Beamer beamer = (Beamer) player.getInventory().getItem("beamer"); if (beamer.isCharged()) { Room vRoom = beamer.getSavedRoom(); if (!vRoom.equals(player.getCurrentRoom())) { GameEngine.gui.println("FIRE !!!!"); player.changeRoom(vRoom); GameEngine.gui.println(player.getCurrentRoom().getLongDescription()); if(player.getCurrentRoom().getImageName() != null) GameEngine.gui.showImage(player.getCurrentRoom().getImageName()); beamer.setCharged(false); } else { GameEngine.gui.println("You are already in the saved room."); } } else { GameEngine.gui.println("You saved the current room with your beamer."); beamer.setCharged(true); beamer.setSavedRoom(player.getCurrentRoom()); } return false; }
ea11dbdd-5388-45f6-9b91-ba94b05291c0
2
public boolean equals(Object aObject) { if (this == aObject) { return true; } else if (aObject instanceof DAOCompeticao) { DAOCompeticao lDAOCompeticaoObject = (DAOCompeticao) aObject; boolean lEquals = true; return lEquals; } return false; }
62ce08de-c310-4048-aa87-7d6b85cb35b2
4
public void eseguiSimulazioneConvalida() { /* Inizializzazione vettore. */ ArrayList<Double> tempiUscitaMedi = new ArrayList<Double>(); /* Cicla sui job. */ for (int i = passo ; i <= jobTotali ; i += passo) { seed_arrivi = 229; seed_routing = 227; seed_routing_cpu = 135; seed_cpu_1 = 233; seed_cpu_2 = 135; seed_io_1 = 255; seed_io_2 = 135; seed_io_3 = 273; /* Cicla sui run. */ for (int j = 1 ; j <= run ; j++) { /* Genera un sistema a singola CPU e registra la media dei tempi dei job. */ SingleCPUConvalida singleCPU = new SingleCPUConvalida(seed_arrivi, seed_cpu_1, seed_io_1, seed_routing, i); tempiUscitaMedi.add(singleCPU.simula()); /* Aggiornamento dei seeds. */ seed_arrivi = singleCPU.getGeneratoreArrivi().getX0(); seed_cpu_1 = singleCPU.getCpu().getGeneratore().getX0(); seed_io_1 = singleCPU.getIo().getGeneratore().getX0(); seed_routing = singleCPU.getGeneratoreRouting().getX0(); } /* Calcolo della media sperimentale. */ double somma = 0.0; for (Double d : tempiUscitaMedi) somma += d; somma = somma / run; /* Calcolo della deviazione standard sperimentale. */ double sd = 0.0; for (Double d : tempiUscitaMedi) sd += Math.pow(d - somma, 2); sd /= (run - 1); /* Registraione dei valori. */ avgs.add(somma); sds.add(sd); /* Reset del vettore. */ tempiUscitaMedi = new ArrayList<Double>(); } /* Stampa i vettori per i grafici. */ print(jobTotali); }
76f21d81-5cf8-4535-b16a-8be0684ce995
7
public static int discrete(double[] a) { double EPSILON = 1E-14; double sum = 0.0; for (int i = 0; i < a.length; i++) { if (a[i] < 0.0) throw new IllegalArgumentException("array entry " + i + " is negative: " + a[i]); sum = sum + a[i]; } if (sum > 1.0 + EPSILON || sum < 1.0 - EPSILON) throw new IllegalArgumentException("sum of array entries not equal to one: " + sum); // the for loop may not return a value when both r is (nearly) 1.0 and when the // cumulative sum is less than 1.0 (as a result of floating-point roundoff error) while (true) { double r = uniform(); sum = 0.0; for (int i = 0; i < a.length; i++) { sum = sum + a[i]; if (sum > r) return i; } } }
a8757093-8415-45d3-a896-4a2bbf7ae134
9
protected void fillSpectrum() { for (int i = 0; i < spectrum.length; i++) { spectrum[i] = (float) Math.sqrt(real[i] * real[i] + imag[i] * imag[i]); } if (whichAverage == LINAVG) { int avgWidth = (int) spectrum.length / averages.length; for (int i = 0; i < averages.length; i++) { float avg = 0; int j; for (j = 0; j < avgWidth; j++) { int offset = j + i * avgWidth; if (offset < spectrum.length) { avg += spectrum[offset]; } else { break; } } avg /= j + 1; averages[i] = avg; } } else if (whichAverage == LOGAVG) { for (int i = 0; i < octaves; i++) { float lowFreq, hiFreq, freqStep; if (i == 0) { lowFreq = 0; } else { lowFreq = (sampleRate / 2) / (float) Math.pow(2, octaves - i); } hiFreq = (sampleRate / 2) / (float) Math.pow(2, octaves - i - 1); freqStep = (hiFreq - lowFreq) / avgPerOctave; float f = lowFreq; for (int j = 0; j < avgPerOctave; j++) { int offset = j + i * avgPerOctave; averages[offset] = calcAvg(f, f + freqStep); f += freqStep; } } } }
f0feb9a7-9c57-4a0a-9456-d56a36eb4dba
5
public void fadeOutIn( FilenameURL filenameURL, long milisOut, long milisIn ) { if( !toStream ) { errorMessage( "Method 'fadeOutIn' may only be used for " + "streaming and MIDI sources." ); return; } if( filenameURL == null ) { errorMessage( "Filename/URL not specified in method 'fadeOutIn'." ); return; } if( milisOut < 0 || milisIn < 0 ) { errorMessage( "Miliseconds may not be negative in method " + "'fadeOutIn'." ); return; } fadeOutMilis = milisOut; fadeInMilis = milisIn; fadeOutGain = 1.0f; lastFadeCheck = System.currentTimeMillis(); synchronized( soundSequenceLock ) { if( soundSequenceQueue == null ) soundSequenceQueue = new LinkedList<FilenameURL>(); soundSequenceQueue.clear(); soundSequenceQueue.add( filenameURL ); } }
f1973bb3-62de-4dd8-8e20-50c5e655d065
4
@Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { // hack TreePath path = tree.getPathForRow(row); if (path != null) { TreeNode tn = (TreeNode)path.getLastPathComponent(); if (tn != null && tn.getClass() == FileTreeNode.class) { if (((FileTreeNode)tn).isFile) setLeafIcon(fileIcon); else setLeafIcon(folderClosedIcon); } } return super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus); }
b7d8454e-bb2c-47b6-9f27-3982702166b2
3
@Override public void onCollideWithEntity(Entity entity) { if(timeAlive >= lifeTime && !this.hasCollided && !(entity instanceof EntityPlayer)) { this.hasCollided = true; world.attemptAttack(this, this.getBB(this.getCoords()), this.getFacing().copy().normalise(), this.damage, this.knockback); } }
2d078087-b3f0-4bf4-8015-7b4f5d08900f
1
private void copyHashMap(HashMap from, HashMap to) { to.clear(); Iterator it = from.keySet().iterator(); while (it.hasNext()) { String key = (String) it.next(); String value = (String) from.get(key); to.put(key,value); } }
82b8e14a-1777-43c9-abf3-af91d94d44df
5
private void updatePicture() { BufferedImage bufferedImage = null; try { Iterator<ImageReader> readers = ImageIO .getImageReadersByMIMEType(mimeType); ImageInputStream iis = ImageIO .createImageInputStream(new ByteArrayInputStream(image)); if (readers.hasNext()) { ImageReader reader = readers.next(); reader.setInput(iis); bufferedImage = reader.read(0); } } catch (IOException ioe) { ioe.printStackTrace(); } picture.setText(""); if (bufferedImage != null) { picture.setIcon(new ImageIcon(bufferedImage.getScaledInstance(200, -1, Image.SCALE_SMOOTH))); } if (mimeType != null) { info.setText("MIME type: " + mimeType + "\n" + (date == null ? "" : "Date: " + date)); } repaint(); revalidate(); }
5cf9c6ac-2381-4140-b9bf-ca8325b87412
1
public void untimed() { boolean captured = lock.tryLock(); try { System.out.println("tryLock(): " + captured); } finally { if (captured) lock.unlock(); } }
cc191e38-1993-4c72-8f5e-020352b66ead
7
public static void main(String[] args) throws Throwable { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int cases = Integer.parseInt(in.readLine()); StringBuilder sb = new StringBuilder( ); for (int i = 0; i < cases; i++) { String line = in.readLine(); int M = 0; int F = 0; for (int j = 0; j < line.length(); j++) { char actual = line.charAt(j); if( Character.isLetter(actual) ){ if( actual == 'M') M++; else if( actual == 'F') F++; } } if(M==F && M > 1 )sb.append("LOOP\n"); else sb.append("NO LOOP\n"); } System.out.print(new String(sb)); }
56633a64-ca23-499e-8852-0161f46e8407
6
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(NewAdminGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(NewAdminGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(NewAdminGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(NewAdminGUI.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 NewAdminGUI().setVisible(true); } }); }
9a181ac0-01bb-45d5-b06c-fed02060b6c9
3
@Override public void setNewPosition(int x, int y) { boolean bottleIsThrowable = mMovementStr == MovementStrategy.ALIVE && bottle != null; if (bottleIsThrowable && rnd.nextInt(30) == 0) { bottle.setNewPosition(getX(), getY()); Field.getInstance().addStationary(bottle); bottle = null; } super.setNewPosition(x,y); }
6bcacbe6-9be0-4a0f-ab06-47f2cccc4563
4
Object getParameter(int position) { if (position >= 0 && position < values.length) { if (values[position] == null) { try { values[position] = types[position].newInstance(); } catch (Exception ex) { throw new RuntimeException(ex); } } return values[position]; } else { return null; } }
f72e0f6e-7813-44c3-94ad-8f0e12416907
7
public int getTextureForDownloadableImage(String par1Str, String par2Str) { ThreadDownloadImageData var3 = (ThreadDownloadImageData)this.urlToImageDataMap.get(par1Str); if (var3 != null && var3.image != null && !var3.textureSetupComplete) { if (var3.textureName < 0) { var3.textureName = this.allocateAndSetupTexture(var3.image); } else { this.setupTexture(var3.image, var3.textureName); } var3.textureSetupComplete = true; } return var3 != null && var3.textureName >= 0 ? var3.textureName : (par2Str == null ? -1 : this.getTexture(par2Str)); }
a3ff991c-1ed9-4f0c-b6ff-7258acb40569
7
@Override public String getAnswer() throws Exception { //Reworked this to use a boolean cache instead of a Set for a major jump in performance. //Max value is x^2 + 2^3 + 2^4 int max = (int) sqrt(TARGET - 8 - 16); Iterable<Long> primes = getPrimes(max); boolean[] cache = new boolean[TARGET]; int count = 0; for (long p4 : primes) { long c = p4 * p4 * p4 * p4; if (c > TARGET) break; for (long p3 : primes) { long b = p3 * p3 * p3; if (b + c > TARGET) break; for (long p2 : primes) { long a = p2 * p2; if (a + b + c > TARGET) break; if (!cache[(int)(a + b + c)]) { cache[(int)(a + b + c)] = true; count++; } } } } return Integer.toString(count); // Collection<Long> values = new HashSet<Long>(); // for (long p4 : primes) { // long c = p4 * p4 * p4 * p4; // if (c > TARGET) // break; // // for (long p3 : primes) { // long b = p3 * p3 * p3; // if (b + c > TARGET) // break; // // for (long p2 : primes) { // long a = p2 * p2; // if (a + b + c > TARGET) // break; // // values.add(a + b + c); // // } // } // } // // return Integer.toString(values.size()); }
a31cd477-7134-4c32-a888-96ea7533b1bb
1
Hashtable getHiddenMethods() { if (hiddenMethods == null) hiddenMethods = new Hashtable(); return hiddenMethods; }
d479473f-cee0-461a-8e0e-eded39e218dd
9
public boolean solve() { Scanner sc = new Scanner(System.in); pattern = sc.next(); while (sc.hasNext()) { int openCost = sc.nextInt(); int closeCost = sc.nextInt(); bracketCosts.add(new Cost(openCost, closeCost)); } int currIndex = 0; int balance = 0; totalCost = 0; for (int i = 0; i < pattern.length(); i++) { char c = pattern.charAt(i); if (c != '?') { resultBuilder.append(c); if (c == '(') balance++; else balance--; assert balance >= -1; if (balance < 0) { boolean status = replace(); if (!status) return false; balance += 2; } continue; } resultBuilder.append(')'); Cost cost = bracketCosts.get(currIndex++); rBrackets.add(new RightBracket(cost.openCost - cost.closeCost, i)); totalCost += cost.closeCost; balance--; assert balance >= -1; if (balance < 0) { boolean status = replace(); if (!status) return false; balance += 2; } } if (balance != 0) return false; System.out.printf("%d\n%s\n", totalCost, resultBuilder.toString()); return true; }
e5c07668-406d-4613-bba8-5f5f6cf9906a
2
private void paintBoard(Graphics graphics) { for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { graphics.setColor(BOARD_COLOR); graphics.drawRect(STARTING_X_INDEX + (j * SIZE_OF_SQUARE), STARTING_Y_INDEX + (i * SIZE_OF_SQUARE), SIZE_OF_SQUARE, SIZE_OF_SQUARE); } } }
d41a1117-137b-415c-8e6f-c26e413e0b13
8
public Object nextValue() throws JSONException { char c = nextClean(); String s; switch (c) { case '"': case '\'': return nextString(c); case '{': back(); return new JSONObject(this); case '[': case '(': back(); return new JSONArray(this); } /* * Handle unquoted text. This could be the values true, false, or * null, or it can be a number. An implementation (such as this one) * is allowed to also accept non-standard forms. * * Accumulate characters until we reach the end of the text or a * formatting character. */ StringBuffer sb = new StringBuffer(); while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) { sb.append(c); c = next(); } back(); s = sb.toString().trim(); if (s.equals("")) { throw syntaxError("Missing value"); } return JSONObject.stringToValue(s); }
456e180c-258e-495f-a99f-104d63a94025
2
public void showStorage(){ System.out.println("Total Balance : " + access(Accesscreate())); if(characterList.size() != 0){ System.out.println("List character : "); for(Character character : characterList){ System.out.println("character :" + character.toString()); } }else{ System.out.println("There is no character in list"); } System.out.println(); }
dda99fd8-90a7-44a0-baa9-ade2e2c8d000
0
public int getUserAccess() { return userAccess; }
8e370dc3-cc06-41f0-ac02-642c30746e0f
6
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(BRIDClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(BRIDClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(BRIDClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(BRIDClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* * Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { new BRIDClient().setVisible(true); } }); }
a94f5b65-f07d-4ede-9ae7-316edfb7fa1b
7
protected void renderHealthbars(Rendering rendering, Base base) { if (! structure.intact()) return ; if (healthbar == null) healthbar = new Healthbar() ; healthbar.level = structure.repairLevel() ; final BaseUI UI = (BaseUI) PlayLoop.currentUI() ; if ( UI.selection.selected() != this && UI.selection.hovered() != this && healthbar.level > 0.5f ) return ; final int NU = structure.numUpgrades() ; healthbar.size = (radius() * 50) ; healthbar.size *= 1 + Structure.UPGRADE_HP_BONUSES[NU] ; healthbar.matchTo(buildSprite) ; healthbar.position.z += height() + 0.1f ; rendering.addClient(healthbar) ; if (base() == null) healthbar.full = Colour.LIGHT_GREY ; else healthbar.full = base().colour ; if (structure.needsUpgrade()) { Healthbar progBar = new Healthbar() ; progBar.level = structure.upgradeProgress() ; progBar.size = healthbar.size ; progBar.position.setTo(healthbar.position) ; progBar.yoff = Healthbar.BAR_HEIGHT ; progBar.full = Colour.GREY ; progBar.empty = Colour.GREY ; progBar.colour = Colour.WHITE ; //paler version of main bar colour? rendering.addClient(progBar) ; } }
96988b9c-37d5-4433-96a9-5f0fd5c7197a
4
private void addStringFromDir(File dir) { System.out.println("addString"); File file = dir; BufferedReader fin = null; try { fin = new BufferedReader(new FileReader(file)); } catch (FileNotFoundException e1) { e1.printStackTrace(); } String str = null; try { str = fin.readLine(); } catch (IOException e) { e.printStackTrace(); } while (str != null) { StringList.add(str); try { str = fin.readLine(); } catch (IOException e) { e.printStackTrace(); } } }
b2a76a11-4adf-4520-a51d-9c2aba167ac4
2
public String getParknameByPID(Statement statement,String PID)//根据PID获取停车场名 { String result = null; sql = "select parkname from Park where PID = '" + PID +"'"; try { ResultSet rs = statement.executeQuery(sql); while (rs.next()) { result = rs.getString("parkname"); } } catch (SQLException e) { System.out.println("Error! (from src/Fetch/Park.getParknameByPID()"); // TODO Auto-generated catch block e.printStackTrace(); } return result; }
8d66fd9f-9695-472d-95a4-34de00b469da
7
@Override public void actionPerformed(ActionEvent evt) { if (evt.getSource().equals(editButton)) { setEditFieldsEditable(true); riverList.setEnabled(false); setButtonMode(1); } if (evt.getSource().equals(newButton)) { riverListModel.insertElementAt(MainWindow.riverDB.newRiver (), riverList.getSelectedIndex()+1); riverList.setSelectedIndex(riverList.getSelectedIndex()+1); setEditFieldsEditable(true); riverList.setEnabled(false); setButtonMode(1); } if (evt.getSource().equals(copyButton)) { copySelectedRiver (); } if (evt.getSource().equals(deleteButton)) { deleteSelectedRiver (); } if (evt.getSource().equals(okButton)) { setEditFieldsEditable(false); riverList.setEnabled(true); setButtonMode(0); // store changed data to object storeEditData (); } if (evt.getSource().equals(cancelButton)) { setEditFieldsEditable(false); riverList.setEnabled(true); setButtonMode(0); refreshEditData (); } if (evt.getSource().equals(unitOfWaterLevelCombo)) { minWaterLevelUnitField.setText (unitOfWaterLevelCombo.getSelectedItem().toString()); maxWaterLevelUnitField.setText (unitOfWaterLevelCombo.getSelectedItem().toString()); } }
77edf2ac-9ca7-41fe-847a-d5eac098e254
0
public void setUsed(Boolean used) { this.used = used; }
035e20a3-4887-465a-bddb-8a030c82a5dc
4
public int[] bothUtility(){ int blueUtil = 0; int greenUtil = 0; for(int i = 0; i < boardSize; i++) { for(int j = 0; j <boardSize; j++) { COLOR myColor=this.board.get(i).get(j).color; if( myColor== COLOR.BLUE) { blueUtil += this.board.get(i).get(j).weight; }else if(myColor == COLOR.GREEN) { greenUtil += this.board.get(i).get(j).weight; } } } int[] result=new int[2]; result[0]=blueUtil;result[1]=greenUtil; return result; }
f88b6fd9-b38d-4003-ae85-ce0d53bd8410
4
public void clearCurrent() { int position; ItemPanel itemPanel; for ( position = 0; position < Data.INVEN_SLOTS; position++ ) { itemPanel = (ItemPanel) panelInven.getComponent( position ); setItemPanel( itemPanel, null ); } // for for ( position = 0; position < Data.COIN_SLOTS; position++ ) { itemPanel = (ItemPanel) panelCoin.getComponent( position ); setItemPanel( itemPanel, null ); } // for for ( position = 0; position < Data.ARMOR_SLOTS; position++ ) { itemPanel = (ItemPanel) panelArmor.getComponent( position ); setItemPanel( itemPanel, null ); } // for for ( position = 0; position < Data.ACCESS_SLOTS; position++ ) { itemPanel = (ItemPanel) panelAccess.getComponent( position ); setItemPanel( itemPanel, null ); } // for } // clearCurrent ------------------------------------------------------------
9b620975-1616-4931-9f03-2d61f586a30b
0
public boolean isHorizontal() { return horizontal; }
a50818e6-8974-4ea5-87ce-3759e6dab811
8
public String toString() { int level = level(); char[] tab = new char[level]; for(int i = 0; i < level; i++) { tab[i] = '\t'; } String tabs = new String(tab); StringBuilder toReturn = new StringBuilder(); int longestKey = 0, extraWidth = 4; for(String key : table.keySet()) { longestKey = Math.max(longestKey, table.get(key).toString().length()); } char[] tableTopBottom = new char[longestKey+extraWidth]; for(int i = 0; i < tableTopBottom.length; i++) { tableTopBottom[i] = '-'; } String tableSeparator = new String(tableTopBottom); toReturn.append(String.format("%s%s\n", tabs, tableSeparator)); for(String key : table.keySet()) { if(table.get(key) instanceof ClassToken || table.get(key) instanceof MethodToken || table.get(key) instanceof IfToken || table.get(key) instanceof ElseToken) { toReturn.append(String.format(String.format("%%s| %%%ds |\n%%s\n", longestKey+extraWidth-4), tabs, table.get(key).toString(), table.get(key).myContext)); } else { toReturn.append(String.format(String.format("%%s| %%%ds |\n", longestKey+extraWidth-4), tabs, table.get(key).toString())); } } toReturn.append(String.format("%s%s", tabs, tableSeparator)); return toReturn.toString(); }
49981229-0e2c-478d-8a4e-5d0f5a0e02e0
9
public ArrayList<Integer> postorderTraversal(TreeNode root) { if (root == null) return new ArrayList<Integer>(); ArrayList<Integer> result = new ArrayList<Integer>(); Stack<TreeNode> stack = new Stack<TreeNode>(); TreeNode p = root; boolean inLeft = true; while (p != null) { if (p.left != null) { stack.push(p); p = p.left; } else if (p.left == null && p.right != null) { stack.push(p); p = p.right; } else //p->left == NULL && p->right == NULL { result.add(p.val); TreeNode temp=p; while (!stack.empty()) { if (stack.peek().right == null || stack.peek().right == temp) { result.add(stack.peek().val); temp=stack.peek(); stack.pop(); } else break; } if (stack.empty()) p = null; else p = stack.peek().right; } } return result; }
7d807b66-1776-4b74-8802-f831fdfd8a1a
1
public static Test suite() { try { endpointURL = new URL(endpointURLString); } catch (MalformedURLException e) { } TestSuite testSuite = new TestSuite(); testSuite.addTest(new UnitTest("testMakeValidConstantName")); testSuite.addTest(new UnitTest("testCycAccessInitialization")); testSuite.addTest(new UnitTest("testBinaryCycConnection1")); testSuite.addTest(new UnitTest("testBinaryCycConnection2")); testSuite.addTest(new UnitTest("testBinaryCycAccess1")); testSuite.addTest(new UnitTest("testBinaryCycAccess2")); testSuite.addTest(new UnitTest("testBinaryCycAccess3")); testSuite.addTest(new UnitTest("testBinaryCycAccess4")); testSuite.addTest(new UnitTest("testBinaryCycAccess5")); testSuite.addTest(new UnitTest("testBinaryCycAccess6")); testSuite.addTest(new UnitTest("testBinaryCycAccess7")); testSuite.addTest(new UnitTest("testBinaryCycAccess8")); testSuite.addTest(new UnitTest("testBinaryCycAccess9")); testSuite.addTest(new UnitTest("testBinaryCycAccess10")); /* testSuite.addTest(new UnitTest("testBinaryCycAccess11")); */ testSuite.addTest(new UnitTest("testBinaryCycAccess12")); testSuite.addTest(new UnitTest("testBinaryCycAccess13")); testSuite.addTest(new UnitTest("testGetGafs")); testSuite.addTest(new UnitTest("testGetCycImage")); testSuite.addTest(new UnitTest("testGetELCycTerm")); testSuite.addTest(new UnitTest("testBinaryCycAccess14")); testSuite.addTest(new UnitTest("testBinaryCycAccess15")); testSuite.addTest(new UnitTest("testBinaryCycAccess16")); testSuite.addTest(new UnitTest("testAssertWithTranscriptAndBookkeeping")); testSuite.addTest(new UnitTest("testBigCycList")); testSuite.addTest(new UnitTest("testGetArg2")); testSuite.addTest(new UnitTest("testUnicodeCFASL")); testSuite.addTest(new UnitTest("testHLIDGeneration")); testSuite.addTest(new UnitTest("testHLIDRoundTripConversion")); testSuite.addTest(new UnitTest("testCycLeaseManager")); testSuite.addTest(new UnitTest("testInferenceProblemStoreReuse")); testSuite.addTest(new UnitTest("testInvalidTerms")); testSuite.addTest(new UnitTest("testCycSymbolLocaleIndependence")); return testSuite; }
fb250e6f-0112-435f-ac1e-066f1a610354
6
@Override public byte[] drawInvoice() throws IOException, COSVisitorException { PDDocument doc = null; try { doc = new PDDocument(); PDPage page = new PDPage(); doc.addPage(page); PDPageContentStream contentStream = new PDPageContentStream(doc, page); PDFont pdfFont = PDType1Font.HELVETICA; float fontSize = 25; float leading = 1.5f * fontSize; PDRectangle mediabox = page.findMediaBox(); float margin = 72; float width = mediabox.getWidth() - 2 * margin; float startX = mediabox.getLowerLeftX() + margin; float startY = mediabox.getUpperRightY() - margin; String text = "I am trying to create a PDF file with a lot of text contents in the document. I am using PDFBox"; List<String> lines = new ArrayList<>(); int lastSpace = -1; while (text.length() > 0) { int spaceIndex = text.indexOf(' ', lastSpace + 1); if (spaceIndex < 0) { lines.add(text); text = ""; } else { String subString = text.substring(0, spaceIndex); float size = fontSize * pdfFont.getStringWidth(subString) / 1000; if (size > width) { if (lastSpace < 0) // So we have a word longer than the line... draw it anyways lastSpace = spaceIndex; subString = text.substring(0, lastSpace); lines.add(subString); text = text.substring(lastSpace).trim(); lastSpace = -1; } else { lastSpace = spaceIndex; } } } contentStream.beginText(); contentStream.setFont(pdfFont, fontSize); contentStream.moveTextPositionByAmount(startX, startY); for (String line: lines) { contentStream.drawString(line); contentStream.moveTextPositionByAmount(0, -leading); } contentStream.endText(); contentStream.close(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); doc.save(byteArrayOutputStream); return byteArrayOutputStream.toByteArray(); } finally { if (doc != null) doc.close(); } }
ea020eb8-a9ca-4a23-901f-68e174ea9aad
9
public static ListNode mergeSortedList(ListNode l1, ListNode l2){ if(l1 == null) return l2; if(l2 == null) return l1; ListNode newHead; ListNode curNode; if(l1.val < l2.val){ newHead = l1; l1 = l1.next; }else { newHead = l2; l2 = l2.next; } curNode = newHead; for (;l1 != null && l2 != null;){ if(l1.val < l2.val){ curNode.next = l1; curNode = curNode.next; l1 = l1.next; }else if(l1.val > l2.val) { curNode.next = l2; curNode = curNode.next; l2 = l2.next; }else { curNode.next = l1; curNode = curNode.next; l1 = l1.next; curNode.next = l2; curNode = curNode.next; l2 = l2.next; } } if(l1 != null){ curNode.next = l1; } if(l2 != null){ curNode.next = l2; } return newHead; }
c90c808d-3115-4682-9a84-f2604159187f
3
public void choisirParametres() { // Initialisation des tailles de grille this.jComboBoxTailleGrilles.removeAllItems(); for(TailleGrille tg : this.TailleGrilles){ this.jComboBoxTailleGrilles.addItem(tg.getX()+"x"+tg.getY()); } // Initialisation des epoques this.jComboBoxEpoques.removeAllItems(); Iterator i = DAOFactory.getInstance().getDAO_Configuration().getAllEpoques().keySet().iterator(); while (i.hasNext()) { this.jComboBoxEpoques.addItem(i.next()); } // Initialisation des difficultees this.jComboBoxDifficultees.removeAllItems(); for(Object diff : DAOFactory.getInstance().getDAO_Parametre().getDifficultees()){ this.jComboBoxDifficultees.addItem((String)diff); } // Initialisation du mode de placement ButtonGroup groupPlacement = new ButtonGroup(); this.jRadioButtonAleatoire.setSelected(true); groupPlacement.add(this.jRadioButtonAleatoire); groupPlacement.add(this.jRadioButtonManuel); // Initialisation du choix concernant la portee ButtonGroup groupPortee = new ButtonGroup(); this.jRadioButtonNon.setSelected(true); groupPortee.add(this.jRadioButtonOui); groupPortee.add(this.jRadioButtonNon); this.popupParametres.setLocationRelativeTo(null); this.setEnabled(false); this.popupParametres.setVisible(true); this.popupParametres.pack(); this.popupParties.dispose(); } // choisirParametres()
b879d50d-87db-49f4-bfc3-139c17b541ca
2
protected void readAttribute(String name, int length, ConstantPool constantPool, DataInputStream input, int howMuch) throws IOException { byte[] data = new byte[length]; input.readFully(data); if ((howMuch & UNKNOWNATTRIBS) != 0) { if (unknownAttributes == null) unknownAttributes = new SimpleMap(); unknownAttributes.put(name, data); } }
a013eb19-625d-40bc-bd87-0e7890135aae
7
private int[] findCloesetPoints(int point, List<Integer> knownPoints, boolean downwards) throws InterpException { int positionLast = -1; int position = -1; for (Integer curPoint : knownPoints) { position = knownPoints.indexOf(curPoint); if ((downwards && curPoint < point) || (!downwards && curPoint > point)) { break; } positionLast = position; } if (positionLast == -1 || position == positionLast) { throw new InterpException( "Given point is too big/small for this section"); } return new int[] { positionLast, position }; }
c7b79923-daeb-4f71-81bd-d83f10e9f5d3
6
@Override public void run() { // get folders int number_of_folders = 0; if (main.arguments.length >= 1 && lib.Console.isNumeric(main.arguments[0])) { number_of_folders = new Integer(main.arguments[0]); } else { number_of_folders = lib.Console.inputInteger("How many student folders?"); } // get assignments int number_of_assignments = 0; if (main.arguments.length >= 2 && lib.Console.isNumeric(main.arguments[1])) { number_of_assignments = new Integer(main.arguments[1]); } else { number_of_assignments = lib.Console.inputInteger("How many assignment folders?"); } // create folders for (int i = 0; i < number_of_folders; i++) { String student_name = lib.Console.input(String.format("[%d/%d] Enter student name:", i + 1, number_of_folders)); // make student folder File student = new File(student_name); student.mkdir(); // make a log file lib.log.write("Student folder created.", student); // make assignment folders for (int j = 1; j <= number_of_assignments; j++) { File assignment = new File(student, Integer.toString(j)); assignment.mkdir(); } } }
3cb8ff20-ad6f-4c2e-9b3e-0a49826c0581
3
private void isLessThanEqualsToDate(Date param, Object value) { if (value instanceof Date) { if (!(param.before((Date) value) || param.equals((Date) value))) { throw new IllegalStateException("Given Date does not lie after the supplied date."); } } else { throw new IllegalArgumentException(); } }
d697d172-508b-4921-9162-f5e34cfa900f
9
public String execute(HttpServletRequest request, HttpServletResponse arg1) throws Exception { ResourceBundle bundle = Resource.getInstance().getRequestToObjectMap(); this.salesItemId = generalTools.NullToEmpty((String)request.getParameter("salesItemId")); this.txtCountryId = generalTools.NullToEmpty((String)request.getParameter("txtCountryId")); if (salesItemId!=null) { SalesItemService salesItemService = new SalesItemService(); salesItemTO = salesItemService.loadRecordById(salesItemId); } // Get country list CountryTO[] listCountry = countryService.getAllCountry(); String btn = (String)request.getParameter("btn"); if (btn!=null) { if (btn.equalsIgnoreCase("Add")){ CountryTO countryTO = countryService.loadRecordById(txtCountryId); request.setAttribute("salesItemTO", salesItemTO); request.setAttribute("countryTO", countryTO); request.setAttribute("hMode", "New"); request.setAttribute("includePage", bundle.getString("admin/salesItemPricingIUD.URL")); return CommandHelper.getTempate(request, bundle); } else if (btn.equalsIgnoreCase("Search")) { this.txtStatus = generalTools.NullToEmpty((String)request.getParameter("txtStatus")); HashMap<String, String> hMap = new HashMap<String, String>(); hMap.put("CountryId", txtCountryId); hMap.put("Status", txtStatus); if (txtCountryId.length()>0) { SalesItemPricingService salesItemPricingService = new SalesItemPricingService(); SalesItemPricingTO[] arrSalesItemPricingTO = salesItemPricingService.searchPageRecord(txtCountryId, txtStatus); if (arrSalesItemPricingTO!=null && arrSalesItemPricingTO.length==0) { hMap.put("Empty", "common.no_record"); } request.setAttribute("arrSalesItemPricingTO", arrSalesItemPricingTO); } else { msg = "alert.insert_mandatory"; } request.setAttribute("listCountry", listCountry); request.setAttribute("salesItemTO", salesItemTO); request.setAttribute("hMap", hMap); request.setAttribute("msg", msg); request.setAttribute("includePage", bundle.getString("admin/salesItemPricing.URL")); return CommandHelper.getTempate(request, bundle); } else if (btn.equalsIgnoreCase(Multilingual.getLabel(null, "common.back"))) { if (salesItemTO!=null) { ProductService productService = new ProductService(); SalesItemProductTO[] listSalesItemProduct = productService.listSalesItemProduct(salesItemTO); salesItemTO.setSalesItemProductList(listSalesItemProduct); } else { msg = "alert.load_record_error"; } // Get sales item category list SalesItemCategoryService salesItemCategoryService = new SalesItemCategoryService(); SalesItemCategoryTO[] listSalesItemCategory = salesItemCategoryService.getAllSalesItemCategory(); // Get product list ProductService productService = new ProductService(); ProductTO[] listAllProduct = productService.getAllProduct(); request.setAttribute("listSalesItemCategory", listSalesItemCategory); request.setAttribute("listAllProduct", listAllProduct); request.setAttribute("salesItemTO", salesItemTO); request.setAttribute("msg", msg); request.setAttribute("includePage", bundle.getString("admin/salesItemIUD.URL")); return CommandHelper.getTempate(request, bundle); } } request.setAttribute("listCountry", listCountry); request.setAttribute("salesItemTO", salesItemTO); request.setAttribute("includePage", bundle.getString("admin/salesItemPricing.URL")); return CommandHelper.getTempate(request, bundle); }
da5ff544-c986-447d-b877-67215949b976
4
public static void exec(String s) { try { String cmd = s + "\n"; try { JFrameMain.proc.getOutputStream().write(cmd.getBytes()); JFrameMain.proc.getOutputStream().flush(); } catch (IOException e) { System.out.println(e.getMessage()); } if (s.equalsIgnoreCase("stop")) { BukkitServer.stop(); } if (s.equalsIgnoreCase("reload")) { BukkitServer.getConnection().stop(); BukkitServer.getConnection().start(); } } catch (Exception e) { } }
ffaa13d6-152b-4a51-ab0f-4475434f6c7d
4
@Override public void moveCursor(int down, int right) { for (int i = 0; i < right; i++) { this.getCursor().movePositionRight(); } for (int i = 0; i > right; i--) { this.getCursor().movePositionLeft(); } for (int i = 0; i < down; i++) { this.getCursor().selectLineDown(); } for (int i = 0; i > down; i--) { this.getCursor().selectLineUp(); } }
353ca6a5-dd6c-4fd1-aac1-7b42898883c8
1
@Test(expected = DuplicateInstanceException.class) public void addDuplicateActivityTest() throws DuplicateInstanceException { Activity activity = null; try { activity = activityService.find(0); } catch (InstanceNotFoundException e) { fail("Activity not exist"); } activityService.create(activity); }
8a8ac40f-c5a3-414c-baef-f0864d1ff1a9
7
public static String camelCaseToUnderline(String name) { final int length = name.length(); boolean inupper = false; StringBuilder stb = new StringBuilder(length); int i = 0; while (i < length) { char c = name.charAt(i); i = i + 1; if(inupper) { if(Character.isLowerCase(c)){ stb.append(c); inupper = false; }else if(i < length && Character.isUpperCase(c) && Character.isLowerCase(name.charAt(i))){ stb.append('_'); stb.append(Character.toLowerCase(c)); inupper = false; }else{ stb.append(Character.toLowerCase(c)); } }else{ if(Character.isUpperCase(c)) { stb.append('_'); stb.append(Character.toLowerCase(c)); inupper = true; }else{ stb.append(c); } } } return stb.toString(); }
d31b9359-9cc0-45a9-83de-a6a096c8e6f9
5
@Override public void ParseIn(Connection Main, Server Environment) { Room Room = Environment.RoomManager.GetRoom(Main.Data.CurrentRoom); if (Room == null || !Room.CheckRights(Main.Data, true) || Room.MoodlightData == null) { return; } Environment.InitPacket(365, Main.ClientMessage); Environment.Append(Room.MoodlightData.Presets.size(), Main.ClientMessage); Environment.Append(Room.MoodlightData.CurrentPreset, Main.ClientMessage); int i = 0; for(MoodlightPreset Preset : Room.MoodlightData.Presets) { Environment.Append(++i, Main.ClientMessage); Environment.Append(Preset.BackgroundOnly?2:1, Main.ClientMessage); Environment.Append(Preset.ColorCode, Main.ClientMessage); Environment.Append(Preset.ColorIntensity, Main.ClientMessage); } Environment.EndPacket(Main.Socket, Main.ClientMessage); }
c9d882c1-fc4f-4dbc-8d1e-ac543fe12ad4
6
public boolean contains(World world, Vector pt) { if (!this.world.getName().equals(world.getName())) { return false; } final double x = pt.getX(); final double y = pt.getY(); final double z = pt.getZ(); return x >= min.getBlockX() && x < max.getBlockX() + 1 && y >= min.getBlockY() && y < max.getBlockY() + 1 && z >= min.getBlockZ() && z < max.getBlockZ() + 1; }
5f239a4b-4abb-494c-94a5-7f1f67309573
7
private static int[] merge(int[] left, int[] right) { int[] merged = new int[left.length + right.length]; int mergedTail = left.length + right.length -1; int leftTail = left.length -1; int rightTail = right.length -1; while(leftTail>=0 && rightTail>=0) { if(left[leftTail] >= right[rightTail]) { merged[mergedTail] = left[leftTail]; leftTail --; mergedTail --; }else { merged[mergedTail] = right[rightTail]; rightTail --; mergedTail --; } } if(leftTail>=0) { while(leftTail>=0) { merged[mergedTail] = left[leftTail]; leftTail --; mergedTail --; } } else if(rightTail >=0) { while(rightTail>=0) { merged[mergedTail] = right[rightTail]; rightTail --; mergedTail --; } } return merged; }
95ef48f1-6bf7-4f83-81d5-adce4ee3c63e
7
public Instances pruneToK(Instances neighbours, double[] distances, int k) { if(neighbours==null || distances==null || neighbours.numInstances()==0) { return null; } if (k < 1) { k = 1; } int currentK = 0; double currentDist; for(int i=0; i < neighbours.numInstances(); i++) { currentK++; currentDist = distances[i]; if(currentK>k && currentDist!=distances[i-1]) { currentK--; neighbours = new Instances(neighbours, 0, currentK); break; } } return neighbours; }
c77be90d-a17d-4852-8848-9830a031ab7c
9
private String digitConver(char digit) { String returnVal; switch(digit) { case '1': returnVal = "壹";break; case '2': returnVal = "贰";break; case '3': returnVal = "叁";break; case '4': returnVal = "肆";break; case '5': returnVal = "伍";break; case '6': returnVal = "陆";break; case '7': returnVal = "柒";break; case '8': returnVal = "捌";break; case '9': returnVal = "玖";break; default: returnVal = "零"; } return returnVal; }
ba14f8b8-da02-435b-9e5c-4a169b68c40f
5
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { Player player = (Player)sender; if(commandLabel.equalsIgnoreCase("ignite")) { if(sender.hasPermission("basics.command.ignite.self")) { if(args.length == 1) { sender.sendMessage(ChatColor.GREEN + "You have been ignited!"); player.setFireTicks(Integer.parseInt(args[0]) * 20); } } if(sender.hasPermission("basics.command.ignite.other")) { if(args.length == 2) { Player tplayer = player.getServer().getPlayer(args[1]); tplayer.setFireTicks(Integer.parseInt(args[0]) * 20); sender.sendMessage(ChatColor.GREEN + "You have ignited " + tplayer); tplayer.sendMessage(ChatColor.GREEN + "You have been ignited by " + sender); } } } return false; }
201337d1-7bba-4c47-88e9-62fc683bd11c
3
public void TheifStall(String stallName, String message, int lvlReq, int XPamount, int item, int itemAmount, int delay, int emote) { if(theifTimer == 0) { if(playerLevel[17] >= lvlReq) { setAnimation(emote); sendMessage("You steal from the "+stallName); sendMessage(message); addItem(item, itemAmount); addSkillXP(XPamount, 17); theifTimer = delay; } else if(playerLevel[17] < lvlReq) { sendMessage("You need a theiving level of "+lvlReq+" to theif from this stall."); } } }
632208e3-daca-45c1-baaa-cd61bbf6e40c
1
public Object mapValue(Object value) { return value instanceof Type ? mapType((Type) value) : value; }
7a9ee528-e6b6-4f57-9015-286e370d3c6a
6
public void printBrake(){ DecimalFormat df = new DecimalFormat("#.000"); IO.println("> Brake Calculation for " + speed + "m/s braking at " + brakerate + " m/s"); IO.print("Cofirm Operation... (y/n) "); Scanner s = new Scanner(System.in); String confirm = s.nextLine(); IO.logln("<IN> " + confirm); if(confirm.equals("y")){ long dtime = System.currentTimeMillis(); final int ispeed = (int) speed; for(int i = 0; i < ispeed/brakerate ; i++){ speed -= brakerate; if(speed < 0){ speed = 0; } distance += speed; IO.print("Time: " + (int)i + "s"); for(int i2 = 0; i2 < 20-Integer.toString(i).length(); i2++){ IO.print(" "); } IO.print("| Speed: " + df.format(speed) + "m/s"); for(int i2 = 0; i2 < 50-String.valueOf(df.format(speed)).length(); i2++){ IO.print(" "); } IO.print("| Distance: " + df.format(distance) + "m"); for(int i2 = 0; i2 < 50-String.valueOf(df.format(distance)).length(); i2++){ IO.print(" "); } IO.println(""); } IO.println("> Operation Completed in " + (int)(System.currentTimeMillis() - dtime)/1000 + "s"); } else { IO.println("> Operation Aborted"); // If reply is 'n' } }
812acd61-1c6c-44d0-92ee-fb8c0bc840ba
5
public CodeMap3y set(final int index, final int value) { final int i0 = index >>> 26; int[][] map1; if (i0 != 0) { if (map == null) map = new int[MAX_INDEX_ZERO][][]; map1 = map[i0]; if (map1 == null) map[i0] = map1 = new int[MAX_INDEX_ONE][]; } else map1 = map10; final int i1 = (index >>> 13) & 0x1fff; int[] map2 = map1[i1]; if (map2 == null) { map1[i1] = map2 = new int[MAX_INDEX_TWO]; for (int i = 0; i < MAX_INDEX_TWO; ++i) map2[i] = NOT_FOUND; } map2[index & 0x1fff] = value; return this; }
a48022d5-dd29-46d9-b4c7-c2ac476dcd97
0
public final int getRowCount() { return data.size(); }
60aaed90-c203-4a71-bb23-3afef771b3df
8
private void readValues(Stream buffer) { do { int configId = buffer.getUnsignedByte(); if (configId == 0) { return; } else if (configId == 1) { anInt390 = buffer.get24BitInt(); method262(anInt390); } else if (configId == 2) { anInt391 = buffer.getUnsignedByte(); } else if (configId == 3) { } else if (configId == 5) { occlude = false; } else if (configId == 6) { buffer.getString(); } else if (configId == 7) { int j = anInt394; int k = anInt395; int l = anInt396; int i1 = anInt397; int j1 = buffer.get24BitInt(); method262(j1); anInt394 = j; anInt395 = k; anInt396 = l; anInt397 = i1; anInt398 = i1; } else { System.out.println("Error unrecognised config code: " + configId); } } while (true); }
a7ba7efa-6a1c-4bf0-8910-df289208ebd2
7
@Override public TrackerResponse sendRequest (TrackerRequest request, long time, TimeUnit unit) { String host = uri.getHost(); int port = uri.getPort(); try (DatagramSocket socket = new DatagramSocket()) { InetAddress addr = InetAddress.getByName(host); // UDP Socket - already bound socket.setSoTimeout((int) (unit.toMillis(time) / 2)); // UDP Datagram - setup of address/port DatagramPacket packet = new DatagramPacket(EMPTY_BYTE_ARR, 0); packet.setAddress(addr); packet.setPort(port); // Byte Array Output/Input Streams for writing/reading the packets ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dataOut = new DataOutputStream(baos); DataInputStream dataIn = null; // Random Transaction ID int action; int recvTransactionId; long connectionId = CONNECTION_ID; int transactionId = RANDOM.nextInt(); // STEP 1: Send the connection message baos.reset(); dataOut.writeLong(connectionId); dataOut.writeInt(0); dataOut.writeInt(transactionId); packet.setData(baos.toByteArray(), 0, 16); socket.send(packet); // STEP 2: Receive the connection message socket.receive(packet); dataIn = new DataInputStream(new ByteArrayInputStream(packet.getData())); action = dataIn.readInt(); recvTransactionId = dataIn.readInt(); connectionId = dataIn.readLong(); if (action != 0 || recvTransactionId != transactionId) { return null; } // STEP 3: Send the announce message baos.reset(); transactionId = RANDOM.nextInt(); dataOut.writeLong(connectionId); dataOut.writeInt(1); dataOut.writeInt(transactionId); dataOut.write(request.getInfoHash().getBytes()); dataOut.write(request.getPeerId().getBytes()); dataOut.writeLong(request.getBytesDownloaded()); dataOut.writeLong(request.getBytesLeft()); dataOut.writeLong(request.getBytesUploaded()); dataOut.writeLong(request.getEvent().getEventInt()); if (request.getIp() == null) { dataOut.writeInt(-1); } else { byte[] ipbuf = request.getIp().getAddress(); if (ipbuf.length != 4) { // IPv6 - Not supported for some reason dataOut.writeInt(-1); } else { dataOut.write(ipbuf, 0, 4); } } dataOut.writeInt(request.getKey()); dataOut.writeInt(request.getNumWant()); dataOut.writeShort((short) request.getPort()); packet.setData(baos.toByteArray(), 0, 98); socket.send(packet); // STEP 4: "Parse" the response packet.setData(new byte[20 + 6 * request.getNumWant()]); socket.receive(packet); dataIn = new DataInputStream(new ByteArrayInputStream(packet.getData())); action = dataIn.readInt(); recvTransactionId = dataIn.readInt(); int interval = dataIn.readInt(); int leechers = dataIn.readInt(); int seeders = dataIn.readInt(); int numPeersRecv = dataIn.available() / 6; byte[] addrBuf = new byte[4]; List<PeerInfo> peers = new ArrayList<PeerInfo>(); for (int i = 0; i < numPeersRecv; i++) { int read = dataIn.read(addrBuf, 0, 4); if (read != 4) { return null; } int recvPort = 0xFFFF & dataIn.readShort(); PeerInfo peer = new PeerInfo(new InetSocketAddress(InetAddress.getByAddress(addrBuf), recvPort), null); peers.add(peer); } return new TrackerResponse(false, null, "", interval, interval, EMPTY_BYTE_ARR, seeders, leechers, peers); } catch (IOException e) { return null; } }
8b296d2b-f27b-44fb-95b7-2af09ffe3651
4
public Value measure(Env env) throws SimPLException { Value v1 = e.measure(env); switch(this.op){ case negative: if(v1.type.typeid == Type.TypeEnum.t_int) { IntValue res = new IntValue(); res.type.typeid = Type.TypeEnum.t_int; res.value = -((IntValue)v1).value; return res; } else { throw new SimPLException("not int",errortype.type_error); } //break; case not: if(v1.type.typeid == Type.TypeEnum.t_bool) { BoolValue res = new BoolValue(); res.type.typeid = Type.TypeEnum.t_bool; res.value = !((BoolValue)v1).value; return res; } else { throw new SimPLException("not bool",errortype.type_error); } //break; } throw new SimPLException("unreachable unary oper"); }
7133379b-f98f-44cd-befd-217a61c7fefc
3
public static Object createObjectViaDefaultConstructor(String className) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { if(className != null) { // Fetch class object ... Class<?> classObj = Class.forName(className); // ... get std constructor for class ... Constructor<?> tConstructor = classObj.getConstructor(); // ... and generate object return tConstructor.newInstance(); } else { throw new ClassNotFoundException("Can not create object since no class name is given."); } }
ff36d365-45c6-4224-9392-4f7febb604bd
1
public AbilityType getAbilityFromHotkey(int x) { if (x < 10) { return player.characterSheet.hotkeys[x - 1]; } return null; }
e0b4137c-7587-4de3-90ff-7c1202e07bad
9
private TreeNodeObject makeRootNode(ResultData result) { // erste Knoten ist Wurzelknoten String rootPid = ""; // alle erzeugten TreeNodeObjekte werden in einer HashMap gespeichert Map<String, TreeNodeObject> hashMap = new HashMap<String, TreeNodeObject>(); // erst werden alle TreeNodeObjekte ohne Untermenüeinträge erstellt if(!result.hasData()) { _debug.warning("Zum Systemobject " + result.getObject().getName() + " gibt es keine Daten!"); return new TreeNodeObject(""); } Data data = result.getData(); Data menu = data.getItem("Menü"); Data.Array menuArray = menu.asArray(); for(int i = 0; i < menuArray.getLength(); i++) { Data menuData = menuArray.getItem(i); // den i-ten Eintrag String pid = menuData.getTextValue("Pid").getText(); String name = menuData.getTextValue("Name").getText(); TreeNodeObject treeNode = new TreeNodeObject(name, pid); Data.Array filterArray = menuData.getArray("Filter"); for(int j = 0; j < filterArray.getLength(); j++) { Data filter = filterArray.getItem(j); String criteria = filter.getTextValue("Kriterium").getText(); String[] values = filter.getTextArray("Wert").getTextArray(); treeNode.addFilter(new Filter(criteria, values, _connection)); } // speichern der Knoten in einer HashMap hashMap.put(pid, treeNode); // Wurzelknoten merken if(i == 0) { rootPid = pid; } } // Untermenü-Verweise werden erstellt. for(int i = 0; i < menuArray.getLength(); i++) { Data menuData = menuArray.getItem(i); String[] subItems = menuData.getArray("UnterMenü").asTextArray().getTextArray(); if(subItems.length > 0) { String pid = menuData.getTextValue("Pid").getText(); TreeNodeObject treeNode = hashMap.get(pid); // hierzu Untermenüs erstellen for(int j = 0; j < subItems.length; j++) { String subItem = subItems[j]; // gibt es zu dieser Pid überhaupt einen Eintrag? if(hashMap.containsKey(subItem)) { treeNode.addChild(hashMap.get(subItem)); } else { _debug.warning("Zur Untermenü-Pid " + subItem + " gibt es kein Data-Objekt!"); } } } } TreeNodeObject rootNode = hashMap.get(rootPid); if(rootNode != null) { return rootNode; } else { return new TreeNodeObject(""); } }
1d7e7b65-6ac2-43d4-9c4d-d70f38f2123e
8
public static void initPermissions() { createFiles(); // make sure the files exist, if not, create them try { Server.display("Loading permissions from file..."); BufferedReader inputFile = null; try { // Clear arrays lstAdmin.clear(); lstOps.clear(); lstVoice.clear(); lstBanned.clear(); String str; int theCount = 0; // Ah! Ah! Ah! // Administrators lstAdmin.add("Console".toLowerCase()); // console should always be an administrator inputFile = new BufferedReader(new FileReader("data" + File.separator + "users-admins.txt")); while ((str = inputFile.readLine()) != null) { lstAdmin.add(str.toLowerCase()); theCount++; } Server.display(" - Loaded " + theCount + " administrators from file."); inputFile.close(); theCount = 0; // Operators inputFile = new BufferedReader(new FileReader("data" + File.separator + "users-ops.txt")); while ((str = inputFile.readLine()) != null) { lstOps.add(str.toLowerCase()); theCount++; } Server.display(" - Loaded " + theCount + " operators from file."); inputFile.close(); theCount = 0; // Voiced users inputFile = new BufferedReader(new FileReader("data" + File.separator + "users-voiced.txt")); while ((str = inputFile.readLine()) != null) { lstVoice.add(str.toLowerCase()); theCount++; } Server.display(" - Loaded " + theCount + " voiced users from file."); inputFile.close(); theCount = 0; // Banned users inputFile = new BufferedReader(new FileReader("data" + File.separator + "users-banned.txt")); while ((str = inputFile.readLine()) != null) { lstBanned.add(str.toLowerCase()); theCount++; } Server.display(" - Loaded " + theCount + " banned users from file."); inputFile.close(); theCount = 0; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (inputFile != null) { inputFile.close(); } } } catch (Exception ex) { Server.display("Cannot load permissions lists from file: " + ex.toString()); } }
d6b251e4-4e37-4e21-bd86-df9815c7020c
4
private List<Integer> findSharedMovies(int user1, int user2) { List<Integer> sharedMovies = new ArrayList<Integer>(); HashSet<Integer> user1Movies = userRatedMovies.get(user1); HashSet<Integer> user2Movies = userRatedMovies.get(user2); if (user1Movies == null || user2Movies == null) { return sharedMovies; } Iterator<Integer> it = user1Movies.iterator(); while (it.hasNext()) { Integer value = (Integer) it.next(); if (user2Movies.contains(value)) { sharedMovies.add(value); } } return sharedMovies; }
f1d1d068-e25d-4310-97c7-8e12d1772952
8
public static boolean overlaps(Rectangle r1, Rectangle r2){ //check if r2's verticies are contained in r1 if (r1.contains(r2.getLocation())){ return true; } else if(r1.contains(new Point(r2.x + r2.width, r2.y))){ return true; } else if(r1.contains(new Point(r2.x, r2.y + r2.height))){ return true; } else if(r1.contains(new Point(r2.x + r2.width, r2.y + r2.height))){ return true; } //check if r1's verticies are contained in r2 if (r2.contains(r1.getLocation())){ return true; } else if(r2.contains(new Point(r1.x + r1.width, r1.y))){ return true; } else if(r2.contains(new Point(r1.x, r1.y + r1.height))){ return true; } else if(r2.contains(new Point(r1.x + r1.width, r1.y + r1.height))){ return true; } return false; }
43586403-f218-47bf-836a-e97e7915c3ba
6
@Override public void execute(CommandSender sender, String[] arg1) { if (!CommandUtil.hasPermission(sender, PERMISSION_NODES)) { sender.sendMessage(plugin.NO_PERMISSION); return; } if (arg1.length != 1) { sender.sendMessage(ChatColor.RED + "/" + plugin.accept + " (channel)"); return; } String channelName = arg1[0]; String playerName = sender.getName(); try { if (plugin.getUtilities().chatChannelExists(channelName)) { ChatChannel cc = plugin.getChannel(channelName); if (cc.isInvited(playerName) || CommandUtil.hasPermission(sender, PERMISSION_NODES_OVERRIDE)) cc.acceptInvite(playerName); else sender.sendMessage(plugin.CHANNEL_NO_PERMISSION); } else { sender.sendMessage(plugin.CHANNEL_NOT_EXIST); } } catch (SQLException e) { e.printStackTrace(); } }
bebec32a-3bba-4164-a441-3e5bfc930378
4
public static String readFile(String filename) { //read content from file BufferedReader br = null; String data = ""; try { String sCurrentLine = ""; br = new BufferedReader(new FileReader("" + filename)); while ((sCurrentLine = br.readLine()) != null) { System.out.println(sCurrentLine); data = data + "\n" + sCurrentLine; } } catch (IOException e) { e.printStackTrace(); } finally { try { if (br != null) { br.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return data; }
1a2e583b-066b-4e8a-b967-7f5a94a8c746
8
public static String getMediaDirectory() { String directory = null; boolean done = false; // check if the application properties are null if (appProperties == null) { appProperties = new Properties(); // load the properties from a file try { // get the URL for where we loaded this class Class currClass = Class.forName("FileChooser"); URL classURL = currClass.getResource("FileChooser.class"); URL fileURL = new URL(classURL,PROPERTY_FILE_NAME); String path = fileURL.getPath(); path = path.replace("%20"," "); FileInputStream in = new FileInputStream(path); appProperties.load(in); in.close(); } catch (Exception ex) { directory = null; } } // get the media directory if (appProperties != null) directory = (String) appProperties.get(MEDIA_DIRECTORY); File dirFile = null; // check if the directory exists if (directory != null) dirFile = new File(directory); if (directory == null || !dirFile.exists()) { // try to find the mediasources directory try { // get the URL for where we loaded this class Class currClass = Class.forName("FileChooser"); URL classURL = currClass.getResource("FileChooser.class"); URL fileURL = new URL(classURL,"../mediasources/"); directory = fileURL.getPath(); dirFile = new File(directory); if (dirFile.exists()) { setMediaPath(directory); } } catch (Exception ex) { } } return directory; }
0853ea36-3327-42fd-ab2e-c46c3f428b3e
2
public static void setWordWrapInWindow(IWorkbenchWindow window, boolean state) { if (window == null) { return; } IWorkbenchPage page = window.getActivePage(); // iterate all open editors IEditorReference[] editors = page.getEditorReferences(); for (IEditorReference e : editors) { // get editor and reactivate it IEditorPart editor = e.getEditor(true); WordWrapUtils.setWordWrap(editor, state); } }
d4289c7b-fa35-4456-8624-d81958b2da5d
9
protected void doStart() { if ("".equals(fetchFrequencyTf.getText()) || "".equals(repostFrequencyTf.getText()) || "".equals(repostCountTf.getText()) || "".equals(commentCountTf.getText())) { JOptionPane.showMessageDialog(null, "请输入信息!", "设置", JOptionPane.ERROR_MESSAGE); return; } // 保存设置 try { Properties properties = new Properties(); FileInputStream inStream = new FileInputStream(settingFile); properties.load(inStream); properties.setProperty("FETCH_FREQUENCY", fetchFrequencyTf.getText()); properties.setProperty("FETCH_COUNT", fetchCountTf.getText()); properties.setProperty("REPOST_FREQUENCY", repostFrequencyTf.getText()); properties.setProperty("REPOST_COUNT", repostCountTf.getText()); properties.setProperty("COMMENT_COUNT", commentCountTf.getText()); properties.setProperty("REMARK", remarkTf.getText()); OutputStream outStream = new FileOutputStream(settingFile); properties.store(outStream, "Update setting!"); inStream.close(); outStream.close(); } catch (IOException e) { e.printStackTrace(); JOptionPane.showMessageDialog(null, e.toString(), "保存设置", JOptionPane.ERROR_MESSAGE); return; } robotThread = new Thread(new Runnable() { @Override public void run() { while (1 == 1) { try { autoForward(); try { setDocs("------------------------sleeping...(wait to fetch next time)----------------------------\n", Color.blue, false, 12); robotThread.sleep(fetchFrequencyTf.getInteger().longValue() * 1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); setDocs("\n------------------------------\n" + e.toString() + "\n------------------------------\n\n", Color.red, false, 12); try { robotThread.sleep(60 * 1000); } catch (InterruptedException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } } } } }); startButton.setEnabled(false); stopButton.setEnabled(true); displayEp.setText(""); robotThread.start(); }
de84fe6b-1433-4c5d-9b43-571af490a9ed
7
public static String getInitials(String s, boolean withFirstLetter) { if (s == null) { return null; } StringBuilder sb = new StringBuilder(s.length()); boolean upperCase = false; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c == '_') { upperCase = true; } else if (upperCase) { sb.append(Character.toUpperCase(c)); upperCase = false; } else { sb.append(c); } } s = sb.toString(); sb = new StringBuilder(); if (withFirstLetter) { sb.append(s.charAt(0)); } for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (Character.isUpperCase(c)) { sb.append(Character.toLowerCase(c)); } } return sb.toString(); }
48659f75-2fc8-4f80-b83e-829156352b5a
8
public int reverse(int x) { if (x == 0) { return x; } int val = Math.abs(x); int retVal = 0; while (val > 0) { retVal = retVal * 10 + (val % 10); val = val / 10; } // Checking whether there should be leading zero's? //Print number with leading zero's int zeroval = Math.abs(x); int zeros = 0; if (zeroval % 10 == 0) { while (zeroval > 0) { if (zeroval % 10 == 0) { zeros++; zeroval /= 10; } else { break; } } System.out.print("Number with zero's : "); if (x < 0) { System.out.print("-"); } while (zeros-- > 0) { System.out.print("0"); } System.out.println(retVal); } if (x < 0) { retVal = -retVal; } return retVal; }
857f2b35-b490-46d1-9e14-be75d1a0fa75
2
Context(Object... parameters){ int length = parameters.length/2; Reference[] reference_array = new Reference[length]; for(int i = 0; i < length; i++){ reference_array[i] = new Reference((String)parameters[2*i], (parameters[2*i+1] instanceof Representation)?(Representation)parameters[2*i+1]:new Representation(parameters[2*i+1])); } references = new Representation(FArray, reference_array); }
3d474c16-1947-4a41-9a57-3d8f6c791869
0
@Test public void testAddRedMarker() { System.out.println("addRedMarker"); Cell instance = new Cell(0,0); instance.addRedMarker(0); instance.addRedMarker(1); instance.addRedMarker(2); instance.addRedMarker(3); instance.addRedMarker(4); instance.addRedMarker(5); boolean[] result = instance.getMarkers(false); assertEquals(true, result[0]); assertEquals(true, result[1]); assertEquals(true, result[2]); assertEquals(true, result[3]); assertEquals(true, result[4]); assertEquals(true, result[5]); }
9429349b-dfde-463b-8751-da4dfd702ae6
2
private static int task2() { int sum = 0; int temp = 1; int temp2 = 1; int tempTotal = 0; for (int i = tempTotal; tempTotal < 4000000; i += tempTotal) { tempTotal = temp + temp2; if ((tempTotal % 2) == 0) { sum += tempTotal; } temp = temp2; temp2 = tempTotal; } return sum; }
423e52f8-738b-440a-9ced-b3f47abf22be
0
private void c_OHPage(){ c_OHPane = new JPanel(); c_OHPane.setBackground(SystemColor.activeCaption); c_OHPane.setLayout(null); JLabel lbl_OpeningHour = new JLabel("Opening Hour"); lbl_OpeningHour.setHorizontalAlignment(SwingConstants.CENTER); lbl_OpeningHour.setFont(new Font("Arial", Font.BOLD, 30)); lbl_OpeningHour.setBounds(372, 20, 240, 47); c_OHPane.add(lbl_OpeningHour); OH1.setSelected(db.getClinic().getOpenHr(0, 0)); OH2.setSelected(db.getClinic().getOpenHr(0, 1)); OH3.setSelected(db.getClinic().getOpenHr(1, 0)); OH4.setSelected(db.getClinic().getOpenHr(1, 1)); OH5.setSelected(db.getClinic().getOpenHr(2, 0)); OH6.setSelected(db.getClinic().getOpenHr(2, 1)); OH7.setSelected(db.getClinic().getOpenHr(3, 0)); OH8.setSelected(db.getClinic().getOpenHr(3, 1)); OH9.setSelected(db.getClinic().getOpenHr(4, 0)); OH10.setSelected(db.getClinic().getOpenHr(4, 1)); OH11.setSelected(db.getClinic().getOpenHr(5, 0)); OH12.setSelected(db.getClinic().getOpenHr(5, 1)); OH13.setSelected(db.getClinic().getOpenHr(6, 0)); OH14.setSelected(db.getClinic().getOpenHr(6, 1)); OHT_AS.setValue(db.getClinic().getSession(0)); OHT_AE.setValue(db.getClinic().getSession(1)); OHT_PS.setValue(db.getClinic().getSession(2)); OHT_PE.setValue(db.getClinic().getSession(3)); OHT_np1.setValue(db.getClinic().getNonPHr(0)); OHT_np2.setValue(db.getClinic().getNonPHr(1)); OHT_np3.setValue(db.getClinic().getNonPHr(2)); OHT_np4.setValue(db.getClinic().getNonPHr(3)); OHB_save.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { db.getClinic().setOpenHr(0, 0, OH1.isSelected()); db.getClinic().setOpenHr(0, 1, OH2.isSelected()); db.getClinic().setOpenHr(1, 0, OH3.isSelected()); db.getClinic().setOpenHr(1, 1, OH4.isSelected()); db.getClinic().setOpenHr(2, 0, OH5.isSelected()); db.getClinic().setOpenHr(2, 1, OH6.isSelected()); db.getClinic().setOpenHr(3, 0, OH7.isSelected()); db.getClinic().setOpenHr(3, 1, OH8.isSelected()); db.getClinic().setOpenHr(4, 0, OH9.isSelected()); db.getClinic().setOpenHr(4, 1, OH10.isSelected()); db.getClinic().setOpenHr(5, 0, OH11.isSelected()); db.getClinic().setOpenHr(5, 1, OH12.isSelected()); db.getClinic().setOpenHr(6, 0, OH13.isSelected()); db.getClinic().setOpenHr(6, 1, OH14.isSelected()); db.getClinic().setSession(0, (String)OHT_AS.getValue()); db.getClinic().setSession(1, (String)OHT_AE.getValue()); db.getClinic().setSession(2, (String)OHT_PS.getValue()); db.getClinic().setSession(3, (String)OHT_PE.getValue()); db.getClinic().setNonPH(0, (String)OHT_np1.getValue()); db.getClinic().setNonPH(1, (String)OHT_np2.getValue()); db.getClinic().setNonPH(2, (String)OHT_np3.getValue()); db.getClinic().setNonPH(3, (String)OHT_np4.getValue()); JOptionPane.showMessageDialog(null, "Setting saved","Opening Hour",JOptionPane.PLAIN_MESSAGE); }}); OHB_clinic.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { cardLayout.show(contentPane, "Clinic"); } }); }
96c65e06-cb2d-4767-bc22-b8c0180db6ae
7
public void action(Echeancier e, Etage etage, int date) { System.out.println("Début action"); //La cabine change d'étage this.setEtage(etage); this.setDistanceParcourue(this.getDistanceParcourue() + 1); if (this.etage.getNumero() == ascenseur.getNumEtageLePlusHaut() || this.etage.getNumero() == ascenseur.getNumEtageLePlusBas()) { this.inversePriorite(); } //On fait descendre les passagers qui veulent aller à l'étage courant for (int i = 0; i < this.passagers.length; i++) { Passager p = this.passagers[i]; if (p != null) { if (p.getEtageDestination().equals(etage)) { //Il veut aller ici this.passagers[i] = null; this.setNombrePassagersSorties(this.getNombrePassagersSorties() + 1); } } } //Remplissage de la cabine this.remplirCabine(this.etage.getFileAttente()); boolean traiterAppels = traiter(e, date); if (!traiterAppels) { this.inversePriorite(); traiterAppels = traiter(e, date); } //Si il n'y pas eu d'appels à traiter, cabine à l'arrêt if (!traiterAppels) { this.setPriorite('-'); } }