text
stringlengths
14
410k
label
int32
0
9
private static void db(final String s) { if (Specialize.DEBUG) { System.out.println(s); } }
1
public void dragGestureRecognized(DragGestureEvent dge) { JComponent c = (JComponent) dge.getComponent(); DefaultTransferHandler th = (DefaultTransferHandler) c.getTransferHandler(); Transferable t = th.createTransferable(c); if (t != null) { scrolls = c.getAutoscrolls(); c.setAutoscrolls(false); try { if (c instanceof JLabel && ((JLabel) c).getIcon() instanceof ImageIcon) { Toolkit tk = Toolkit.getDefaultToolkit(); ImageIcon imageIcon = ((ImageIcon) ((JLabel) c).getIcon()); Dimension bestSize = tk.getBestCursorSize(imageIcon.getIconWidth(), imageIcon.getIconHeight()); if (bestSize.width == 0 || bestSize.height == 0) { dge.startDrag(null, t, this); return; } Image image; if (bestSize.width > bestSize.height) { bestSize.height = (int) ((((double) bestSize.width) / ((double) imageIcon.getIconWidth())) * imageIcon.getIconHeight()); } else { bestSize.width = (int) ((((double) bestSize.height) / ((double) imageIcon.getIconHeight())) * imageIcon.getIconWidth()); } image = imageIcon.getImage().getScaledInstance(bestSize.width, bestSize.height, Image.SCALE_DEFAULT); /* We have to use a MediaTracker to ensure that the image has been scaled before we use it. */ MediaTracker mt = new MediaTracker(c); mt.addImage(image, 0, bestSize.width, bestSize.height); try { mt.waitForID(0); } catch (InterruptedException e) { dge.startDrag(null, t, this); return; } Point point = new Point(bestSize.width / 2, bestSize.height / 2); Cursor cursor; try { cursor = tk.createCustomCursor(image, point, "freeColDragIcon"); } catch (RuntimeException re) { cursor = null; } //Point point = new Point(0, 0); dge.startDrag(cursor, t, this); } else { dge.startDrag(null, t, this); } return; } catch (RuntimeException re) { c.setAutoscrolls(scrolls); } } th.exportDone(c, null, NONE); }
9
public double getSternCapacitance(){ if(!this.sternOption){ System.out.println("Class: GouyChapmanStern\nMethod: getSternCapacitance\nThe Stern modification has not been included"); System.out.println("A value of infinity has been returned"); return Double.POSITIVE_INFINITY; } if(!this.surfaceAreaSet){ System.out.println("Class: GouyChapmanStern\nMethod: getSternCapacitance\nThe surface area has not bee included"); System.out.println("A value per square metre has been returned"); return this.sternCap; } if(this.psi0set && this.sigmaSet){ return this.sternCap*this.surfaceArea; } else{ if(this.sigmaSet){ this.getSurfacePotential(); return this.sternCap*this.surfaceArea; } else{ if(this.psi0set){ this.getSurfaceChargeDensity(); return this.sternCap*this.surfaceArea; } else{ System.out.println("Class: GouyChapmanStern\nMethod: getSternCapacitance\nThe value of the Stern capacitance has not been calculated\ninfinity returned"); System.out.println("Neither a surface potential nor a surface charge density have been entered"); return Double.POSITIVE_INFINITY; } } } }
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(Inicio.class .getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Inicio.class .getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Inicio.class .getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Inicio.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 Inicio().setVisible(true); } }); }
6
static int process(String line) { int[] arr = giveArray(line.trim().split(" ")); int n = arr[0], p = arr[1]; if(n == 0 && p == 0) return 0; for(int i = 0; i < n; i++) { readLine(); } String name = null; int met = -1; double best = -1; for(int i = 0; i < p; i++) { String s = readLine().trim(); String[] splts = readLine().trim().split(" "); double price = Double.parseDouble(splts[0]); int req = Integer.parseInt(splts[1]); if(req > met) { name = s; met = req; best = price; } else if(req == met && price < best) { best = price; name = s; } for(int j = 0; j < req; j++) readLine(); } if(ind > 0) System.out.println(); System.out.println("RFP #" + (++ind)); System.out.println(name); return 1; }
9
public static int dehexchar(char c) { if (c >= '0' && c <= '9') { return c - '0'; } if (c >= 'A' && c <= 'F') { return c - ('A' - 10); } if (c >= 'a' && c <= 'f') { return c - ('a' - 10); } return -1; }
6
void print() { System.out.println("@RELATION Untitled"); for(int i = 0; i < m_attr_name.size(); i++) { System.out.print("@ATTRIBUTE " + m_attr_name.get(i)); int vals = valueCount(i); if(vals == 0) System.out.println(" CONTINUOUS"); else { System.out.print(" {"); for(int j = 0; j < vals; j++) { if(j > 0) System.out.print(", "); System.out.print(m_enum_to_str.get(i).get(j)); } System.out.println("}"); } } System.out.println("@DATA"); for(int i = 0; i < rows(); i++) { double[] r = row(i); for(int j = 0; j < r.length; j++) { if(j > 0) System.out.print(", "); if(valueCount(j) == 0) System.out.print(r[j]); else System.out.print(m_enum_to_str.get(j).get((int)r[j])); } System.out.println(""); } }
8
public void removeNode(Byte N) { if(networkTreeMap.containsKey(N)){ for(Object nb : networkTreeMap.get(N).toArray()) { removePath((Byte)nb, N); } } networkTreeMap.remove((byte)N); if(autoUpdate) { update(); } }
3
@Override public void processNPC() { super.processNPC(); target = this.getCombat().getTarget(); if (spawnTime + 300000 < Utils.currentTimeMillis() && !this.getCombat().underCombat()) { finish(); } if (target != null) { if (target instanceof Familiar) { Familiar npc = (Familiar) target; target = npc.getOwner(); } if (target instanceof Player) { if (target.isDead()) this.finish(); } } }
6
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; DataStructure that = (DataStructure) o; if (calibrationKey != that.calibrationKey) return false; if (implementedChannels != that.implementedChannels) return false; if (majorVersion != that.majorVersion) return false; if (standartFamily != that.standartFamily) return false; return true; }
7
private static String convertToHex(byte[] data) { StringBuffer buf = new StringBuffer(); for (int i = 0; i < data.length; i++) { int halfbyte = (data[i] >>> 4) & 0x0F; int two_halfs = 0; do { if ((0 <= halfbyte) && (halfbyte <= 9)) buf.append((char) ('0' + halfbyte)); else buf.append((char) ('a' + (halfbyte - 10))); halfbyte = data[i] & 0x0F; } while(two_halfs++ < 1); } return buf.toString(); }
4
public void printRowResult2(ArrayList<Row> rows, boolean headerLine) { System.out.println("=============================================="); if (rows.size() == 0) { System.out.println("No Result"); } Iterator<Row> it = rows.iterator(); int c = 0; while (it.hasNext()) { Row r = it.next(); if (c == 0) { Iterator<Entry<Field, String>> itFields = r.fields.entrySet() .iterator(); int headLenght = 0; while (itFields.hasNext()) { Entry<Field, String> e = itFields.next(); System.out.print(e.getKey()); headLenght += e.getKey().name.length() + 1; if (itFields.hasNext()) { System.out.print(","); } else { System.out.println(); } } if (headerLine) { for (int i = 1; i < headLenght; i++) { System.out.print("-"); } System.out.println(); } } Iterator<Entry<Field, String>> itFields = r.fields.entrySet() .iterator(); while (itFields.hasNext()) { Entry<Field, String> e = itFields.next(); System.out.print(e.getValue()); if (itFields.hasNext()) { System.out.print(","); } else { System.out.println(); } } c++; } System.out.println("=============================================="); }
9
@Override public boolean isValid(final Object value, final String type, final Dimension dimension) { if (!(value instanceof PostilionAddAmount[])) { return false; } final PostilionAddAmount[] addAmounts = (PostilionAddAmount[]) value; if (addAmounts.length < 1 || addAmounts.length > 6) { return false; } for (final PostilionAddAmount item : addAmounts) { if (item == null) { return false; } if (item.getAccountType() == null) { return false; } if (item.getAmountType() == null) { return false; } if (item.getAmount() == null) { return false; } if (item.getCurrencyCode() == null) { return false; } } return true; }
9
@Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if(Validate.isPlayer(sender)) { sender.sendMessage("§6===== [§b Online Players §6] ====="); for(ServerId sid : ServerId.values()) { if(plugin.getServerManager().getPlayerCount(sid) == 0) continue; StringBuilder players = new StringBuilder(); try { for(int i = 0; i < (plugin.getServerManager().getPlayerCount(sid) > 10 ? 10 : plugin.getServerManager().getPlayerCount(sid)); i++) { if(i == (plugin.getServerManager().getPlayerCount(sid) > 10 ? 10 : plugin.getServerManager().getPlayerCount(sid))-1) { players.append(plugin.getServerManager().getPlayerList(sid).get(i).getPlayerName()); } else { players.append(plugin.getServerManager().getPlayerList(sid).get(i).getPlayerName() + ", "); } } } catch(Exception e) { /* I have a feeling that somehow, and Index out of bounds exception will be thrown if player leaves, almost simulaneously, don't really care though */ } sender.sendMessage("§6" + sid.getDisplayName() + "§7:§b " + players); } } return false; }
8
public void dropInfo(int howMuch) { if ((howMuch & UNKNOWNATTRIBS) != 0) unknownAttributes = null; }
1
public static void main(String[] args) throws IOException { List<String> fileList = unpackTIPP(INPUT_ZIP_FILE, OUTPUT_FOLDER); for (int x = 0; x <= fileList.size() - 1; x++) { System.out.println("fileList" + x + "==" + fileList.get(x)); } String fileURL = "https://raw.githubusercontent.com/CNGL-repo/IA/master/GlobicBootstrapRestApi/leanbacklearning.xml?token=497801__eyJzY29wZSI6IlJhd0Jsb2I6Q05HTC1yZXBvL0lBL21hc3Rlci9HbG9iaWNCb290c3RyYXBSZXN0QXBpL2xlYW5iYWNrbGVhcm5pbmcueG1sIiwiZXhwaXJlcyI6MTQwMzc5NDQyMH0%3D--02553aedb2a5693fe41a7d15a705946f415094e7"; String saveDir = "C:\\Users\\Leroy\\Desktop"; try { Files.downloadFile(fileURL, saveDir); } catch (IOException ex) { ex.printStackTrace(); } }
2
public EntidadBancaria read(int idEntidadBancaria){ try{ String selectEntidad = "SELECT * FROM entidadbancaria where identidad = ?;"; EntidadBancaria entidadBancaria; Connection connection = connectionFactory.getConnection(); PreparedStatement prepared = connection.prepareStatement(selectEntidad); prepared.setInt(1, idEntidadBancaria); ResultSet result = prepared.executeQuery(); if (result.next() == true) { int idEntidad = result.getInt("idEntidad"); String codigoEntidad = result.getString("codigoEntidad"); String nombre = result.getString("nombre"); String cif = result.getString("cif"); String tipoEntidadBancaria = result.getString("tipoEntidadBancaria"); entidadBancaria = new EntidadBancaria(); entidadBancaria.setIdEntidad(idEntidad); entidadBancaria.setNombre(nombre); entidadBancaria.setCodigoEntidadBancaria(codigoEntidad); entidadBancaria.setCif(cif); entidadBancaria.setTipo(TipoEntidadBancaria.valueOf(tipoEntidadBancaria)); if (result.next() == true) { throw new RuntimeException("Hay mas de una sucursal con ese ID"); } } else { entidadBancaria = null; } return entidadBancaria; }catch(Exception ex){ throw new RuntimeException(ex); } }
3
@Override public boolean addMod(String modName) { if (modName == null || modName.length() < 1) return false; if (modName.equalsIgnoreCase("all")) return false; if (!this.modList.contains(modName)) { this.modList.add(modName); this.saveConfig(); return true; } return false; }
4
public CeremonialSword(){ this.name = Constants.CEREMONIAL_SWORD; this.attackScore = 8; this.attackSpeed = 12; this.money = 150; }
0
public void update() { for (int y = 0; y < ySize; y++) { for (int x = 0; x < ySize; x++) { Site site = scape.grid[x][y]; JLabel label = labels[x][y]; double energy = site.getFood(); double div = (255 / scape.maxFood) * energy; int gradient = (int) (255 - div); Color background; background = (gradient > 235) ? new Color(255, 250, 205) : new Color(gradient, 255, gradient); label.setBackground(background); if (site.getAgent() != null) { label.setText("o"); label.setForeground(Color.red); } else { label.setText(""); } } } }
4
public static String createChatLeftMessage(String myName) { JSONObject jsonMsg = new JSONObject() .element( "code", "5" ) .element( "name", myName ); ; return jsonMsg.toString(); }
0
protected static void runLoop() { if (loop) return ; LoadService.loadPackage("src") ; rendering() ; if (scenario != null) { scenario.updateGameState() ; } lastUpdate = lastFrame = timeMS() ; loop = true ; long simTime = 0, renderTime = 0, loopNum = 0 ; while (loop) { final long time = timeMS() ; loopCycle() ; // // Go to sleep until the next round of updates are called for: try { final int frameInterval = (1000 / frameRate), taken = (int) (timeMS() - time), sleeps = Math.max(frameInterval + (SLEEP_MARGIN - taken), 0) ; if (sleeps > 0) Thread.sleep(sleeps) ; simTime += sT ; renderTime += rT ; // // Print out a report on rendering/update times- if desired. if (++loopNum >= 100) { final long totalTime = simTime + renderTime ; if (verbose) I.say( "Time spent on graphics/sim/total: " + (renderTime / loopNum) + " / " + (simTime / loopNum) + " / " + (totalTime / loopNum) ) ; simTime = renderTime = loopNum = 0 ; } } catch (InterruptedException e) {} } Display.destroy() ; java.lang.System.exit(0) ; }
7
private double[] logPToP(double[] llContribution, double[] pPrevious) { double[] p = new double[llContribution.length]; double sum = 0.0; for( int i = 0; i < llContribution.length; ++i) { p[i] = Math.exp(llContribution[i]); sum += p[i]; } // Normalization if( pPrevious != null) if( sum != 0.0) { double sum2 = 0.0; for( int i = 0; i < llContribution.length; ++i) { p[i] = (p[i] / sum) * pPrevious[i]; sum2 += p[i]; } for( int i = 0; i < llContribution.length; ++i) p[i] = (p[i] / sum2); } else for( int i = 0; i < llContribution.length; ++i) p[i] = pPrevious[i]; else for( int i = 0; i < llContribution.length; ++i) p[i] = (p[i] / sum); // the sum can not be zero because at the first time slice there is the class prior return p; }
7
public static LinkedList<Task> smartSearch(String searchLine, LinkedList<Task> bufferedTaskList, SEARCH_TYPES searchType, SEARCH_TYPES searchAlgoType){ //Task that is collated through the searches. LinkedList<Task> matchedTasks = new LinkedList<Task>(); switch (searchAlgoType) { case SEARCH_POWER_SEARCH: LinkedList<LinkedList<?>> returnList = powerSearch(searchLine, matchedTasks, bufferedTaskList, searchType); if (!(returnList.get(0).size() == 0)) { suggestInputs = new LinkedList<String>( (LinkedList<String>)returnList.get(1)); } else { suggestInputs.add(NO_MATCH_FOUND); } return (LinkedList<Task>) returnList.get(0); case TYPE_ALL: case SEARCH_START_LETTER: matchedTasks.addAll(startLetterSearch(searchLine, matchedTasks, bufferedTaskList, searchType)); if (searchAlgoType == SEARCH_TYPES.SEARCH_START_LETTER) { break; } case SEARCH_MATCH_WORD: matchedTasks.addAll(matchWordSearch(searchLine, matchedTasks, bufferedTaskList,searchType, false)); if (searchAlgoType == SEARCH_TYPES.SEARCH_MATCH_WORD) { break; } } return removeDuplicate(matchedTasks); }
8
public static void main(final String[] args) { //Schedule a job for the event-dispatching thread: //creating and showing this application's GUI. String fileToOpen = null; boolean isOpeningClipboard = false; try{ for(int i=0;i<args.length;++i){ String arg = args[i]; if (arg.startsWith("-")){ if (arg.equals("-c") || arg.equals("--clipboard")){ isOpeningClipboard = true; }else if(arg.equals("-h") || arg.equals("--help")){ System.out.println(CMDLINE_HELP_TEXT); System.exit(0); }else throw new RuntimeException("Unexpected argument: "+arg); }else{ if (fileToOpen != null){ throw new RuntimeException("Unexpected argument: "+arg); }else{ fileToOpen = arg; } } } }catch (Exception e){ System.err.println("Error: "+e.getMessage()); System.exit(1); } final String fFileToOpen = fileToOpen; final boolean fOpenClipboard = isOpeningClipboard; javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(fOpenClipboard, fFileToOpen); } }); }
8
protected void setStringToPush(String stringToPush) { /* * if (!automata.StringChecker.isAlphanumeric(stringToPush)) throw new * IllegalArgumentException("Push string must "+ "be alphanumeric!"); */ PushdownAutomaton myPDA = (PushdownAutomaton) this.getAutomaton(); if (myPDA.singleInputPDA && stringToPush.length() > 1) throw new IllegalArgumentException( "Push string must have no more than one character!"); myStringToPush = stringToPush; }
2
public void crossReferenceImplementedInterfaces() throws CrossReferenceException { Set<String> unresolved = new HashSet<String>(); for (String clazz : implementsIndex.keySet()) { Set<String> intfs = implementsIndex.get(clazz); for (String intf : intfs) { if (ignoreScan(intf)) continue; Set<String> xrefAnnotations = classIndex.get(intf); if (xrefAnnotations == null) { unresolved.add(intf); } else { Set<String> classAnnotations = classIndex.get(clazz); if (classAnnotations == null) { classIndex.put(clazz, xrefAnnotations); } else classAnnotations.addAll(xrefAnnotations); for (String annotation : xrefAnnotations) { Set<String> classes = annotationIndex.get(annotation); classes.add(clazz); } } } } if (unresolved.size() > 0) throw new CrossReferenceException(unresolved); }
7
public void ClearCircle(int X, int Y, int R) { // long time = System.nanoTime(); for (int i1 = Math.max(X-(R+1),0); i1 < Math.min(X+(R+1),w); i1 ++) { for (int i2 = Math.max(Y-(R+1),0); i2 < Math.min(Y+(R+1),h); i2 ++) { if (Math.round(Math.sqrt(Math.pow(i1-X,2)+Math.pow(i2-Y,2))) < (R/2)) { if (cellData[i1][i2]==OIL) { if (random.nextInt(10)==2) { cellData[i1][i2]=AIR; //oilExplode(i1, i2); entityList.add(new ExplosionEntity(i1,i2,8,1)); ClearCircle(i1,i2,10); } }//if (cellData[i1][i2]!=STONE) if (cellData[i1][i2]!=CRYSTAL&&cellData[i1][i2]!=ETHER) { cellData[i1][i2]=AIR; } } } } }
7
public static void main(String[] args) throws IOException { Scanner in = new Scanner(System.in); in.useLocale(Locale.US); StringBuilder out = new StringBuilder(); while (in.hasNext()) { int size = (int) in.nextDouble(); double[] d = new double[4]; int allow = 0; for (int i = 0; i < size; i++) { for (int j = 0; j < 4; j++) d[j] = in.nextDouble(); if (d[0] <= 56 && d[1] <= 45 && d[2] <= 25 && d[3] <= 7 || (d[0] + d[1] + d[2] <= 125 && d[3] <= 7)) { out.append("1\n"); allow++; } else out.append("0\n"); } out.append(allow + "\n"); } System.out.print(out); }
9
@command( maximumArgsLength=0, description="null command", permissions="*") public void Null(CommandSender sender,String[] args){ for(Field f:this.getClass().getFields()){ if(f.isAnnotationPresent(config.class)){ try{ if(f.getType()==Location.class){ if(f.get(this)!=null){ sender.sendMessage(f.getName() + ": " + ((Location)f.get(this)).getWorld().getName() + "," + ((Location)f.get(this)).getBlockX() + "," + ((Location)f.get(this)).getBlockY() + "," + ((Location)f.get(this)).getBlockZ()); }else{ sender.sendMessage(ChatColor.GRAY + f.getName() + ": " + "null"); } }else if(f.getType()==List.class){ }else{ if(f.get(this).toString()==""||f.get(this).toString()=="-1"){ sender.sendMessage(ChatColor.GRAY + f.getName() + ": " + f.get(this).toString()); }else{ sender.sendMessage(f.getName() + ": " + f.get(this).toString()); } } }catch(Exception e){ } } } }
8
public E getDataIndex(String pIndex){ E resp = null; for(Nodo<E> i = cabeza; i != null; i=i.getSiguiente()){ if(i.getIndex() == pIndex) resp = i.getDato(); } return resp; }
2
@Override public Object item(int index) { Object value = null; switch (BOMColumn.values()[index]) { case ID: value = getPart().getId(); break; case QUANTITY: value = getQuantity(); break; case COST: value = getCost(); break; case URL: value = getPart().getUrl(); break; case SOURCE: value = getPart().getSourceUrl(); break; case TITLE: value = getPart().getTitle(); break; case VENDOR: value = getVendor(); break; case PROJECT: value = getPart().getProject(); break; } return value; }
8
protected static boolean isReserved(String key) { return "highlight".equals(key) || "name".equals(key) || "resource".equals(key) || "thumbnail".equals(key) || "topic".equals(key) || "upper".equals(key) || "user".equals(key) || "_id".equals(key); }
7
static double computeArea(Circle cs[]){ double ans = 0.0; for (int i = 0; i < cs.length; ++i){ boolean flag = false; for (int j = i+1; j < cs.length; ++j){ if (cs[i].isIntersected(cs[j]) || cs[i].contains(cs[j])){ flag = true; break; } } if (!flag){ ans += cs[i].getArea(); } } return ans; }
5
public void start(String dest, long _maxSize){ if(_maxSize < 0) { maxSize = estimateMaxCapacity(); System.out.println("Maximum estimated size: " + maxSize); } else { maxSize = _maxSize; } try { // send request byte[] rb = new byte[12]; InetAddress address = InetAddress.getByName(dest); System.out.println("Going to connect."); Socket socket = new Socket(address,4466); System.out.println("Connected. Opening stream"); BufferedInputStream in = new BufferedInputStream(socket.getInputStream()); System.out.println("Stream open."); // Open output stream and send maxSize BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream()); byte[] setSize = new byte[1024]; ByteBuffer bb = ByteBuffer.wrap(setSize); bb.putLong(maxSize); out.write(setSize); out.flush(); // Create read buffers and read stream till it closes byte[] readbuffer = new byte[120]; byte[] buffer = new byte[1100]; byte[] processBuffer = new byte[960]; int r = 0; boolean done = false; int bufferLength = 0; while(!done) { while(bufferLength < 960) { r = in.read(readbuffer); System.arraycopy(readbuffer, 0, buffer, bufferLength, r); bufferLength += r; } System.arraycopy(buffer, 0, processBuffer, 0, 960); for(int j=960;j<bufferLength;j++) { buffer[j-960] = buffer[j]; } bufferLength = bufferLength-960; done = processData(processBuffer); } System.out.println("Done"); socket.close(); } catch (Exception ex) { System.err.println("An error has happened!"); Logger.getLogger(DistributedLinkSetClient.class.getName()).log(Level.SEVERE, null, ex); } }
5
public void deleteLines(int[] indices) { int j, k; if (indices != null) { for (int i = 0; i < indices.length; i++) { for (k = indices[i]+i; k > 0; k--) { for (j = 0; j < tailleY; j++) { plateau[k][j] = plateau[k - 1][j]; } } } } }
4
public RoomEvent findRoomEventById(final Long id) { return new RoomEvent(); }
0
public boolean isBossOnStatus() { if(frame == null) buildGUI(); return bossStatus.isSelected(); }
1
@Override public boolean tick(Tickable ticking, int tickID) { if(!super.tick(ticking, tickID)) return false; if(activated() && (tickID==Tickable.TICKID_ELECTRONICS)) { if(!amWearingAt(Wearable.IN_INVENTORY)) setPowerRemaining(powerRemaining()-1); if(powerRemaining()<=0) { setPowerRemaining(0); if(owner() instanceof MOB) { final MOB mob=(MOB)owner(); final CMMsg msg=CMClass.getMsg(mob, this, null,CMMsg.MSG_OK_VISUAL,CMMsg.TYP_DEACTIVATE|CMMsg.MASK_ALWAYS,CMMsg.MSG_OK_VISUAL,fieldDeadStr(mob)); if(mob.location()!=null) mob.location().send(mob, msg); } else activate(false); } } return !amDestroyed(); }
7
public static void htmlWriteFindObjectResponsePage(String modulename, String objectname, String objecttype, Keyword matchtype, org.powerloom.PrintableStringWriter stream) { { Module module = Stella.getStellaModule(modulename, false); if (module == null) { OntosaurusUtil.htmlUnknownModuleResponse(OntosaurusUtil.KWD_RELATION, objectname, modulename, stream); return; } { Object old$Module$000 = Stella.$MODULE$.get(); Object old$Context$000 = Stella.$CONTEXT$.get(); try { Native.setSpecial(Stella.$MODULE$, module); Native.setSpecial(Stella.$CONTEXT$, ((Module)(Stella.$MODULE$.get()))); { List candidateobjects = OntosaurusUtil.findCandidateObjects(objectname, objecttype, matchtype); switch (candidateobjects.length()) { case 0: OntosaurusUtil.htmlUnknownObjectResponse((Stella.stringEqlP(objecttype, "instance") ? OntosaurusUtil.KWD_OBJECT : OntosaurusUtil.KWD_RELATION), objectname, stream); break; case 1: { Surrogate testValue000 = Stella_Object.safePrimaryType(((LogicObject)(candidateobjects.first()))); if (Surrogate.subtypeOfP(testValue000, OntosaurusUtil.SGT_LOGIC_NAMED_DESCRIPTION)) { OntosaurusUtil.htmlWriteRelationResponsePage(((NamedDescription)(OntosaurusUtil.resolveSynonyms(((LogicObject)(candidateobjects.first()))))), stream); } else if (Surrogate.subtypeOfP(testValue000, OntosaurusUtil.SGT_LOGIC_LOGIC_OBJECT)) { OntosaurusUtil.htmlWriteInstanceResponsePage(OntosaurusUtil.resolveSynonyms(((LogicObject)(candidateobjects.first()))), stream); } else { throw ((StellaException)(StellaException.newStellaException("Can't handle object in html-write-find-object-response-page").fillInStackTrace())); } } break; default: OntosaurusUtil.htmlWriteMultipleChoicePage(objectname, candidateobjects, stream); break; } } } finally { Stella.$CONTEXT$.set(old$Context$000); Stella.$MODULE$.set(old$Module$000); } } } }
6
public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add("a"); list.add("b"); list.add("c"); list.add("d"); for(int i = 0; i < list.size();i++){ String value = list.get(i); System.out.println(value); } for(Iterator<String> iter = list.iterator();iter.hasNext();){ String value = iter.next(); System.out.println("Iterator:" + value); } }
2
public static String capitalize(String s) { if (null == s) { return null; } if (s.length() == 0) { return ""; } char char0 = s.charAt(0); if (Character.isUpperCase(char0)) { return s.toString(); } return new StringBuilder(s.length()).append(Character.toUpperCase(char0)).append(s.subSequence(1, s.length())).toString(); }
3
public void connectData() { switch (selectResult) { case 1: // 表示连接的是mysql url = DriverString.MYSQL_JDBC + hostName + ":" + port + "/"; ConnectDB.url = url; ConnectDB.user = name; ConnectDB.password = password; if(dataField.getItemCount() != 0){ dataField.removeAllItems(); } dataField.addItem(StringConstants.SELECT_DATABASE); try { DatabaseMetaData databaseMeta = (DatabaseMetaData)ConnectDB.getConn().getMetaData(); ResultSet resultSet = databaseMeta.getCatalogs(); String dataName = ""; while(resultSet.next()){ dataName = resultSet.getString("TABLE_CAT"); dataField.addItem(dataName); } dataField.setEnabled(true); openConnectBtn.setEnabled(true); } catch (SQLException e) { // TODO Auto-generated catch block Toolkit.getDefaultToolkit().beep(); JOptionPane.showMessageDialog(connectDialog, e.getMessage(), "连接数据库出错", JOptionPane.ERROR_MESSAGE); //e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ ConnectDB.closeConn(); } break; case 2://连接oracl dataName = dataField2.getText().trim(); url = DriverString.ORACLE_JDBC + hostName + ":" + port + ":" + dataName; default: break; } }
6
public String inspect(Object o) { Class c = o instanceof Class ? (Class) o : o.getClass(); StringBuilder sb = new StringBuilder(); sb.append("Class: ").append(c.getName()).append("\n"); sb.append("Methods:\n"); Method[] methods = c.getDeclaredMethods(); for (Method method : methods) { sb .append(Modifier.toString(method.getModifiers())) .append(" ") .append(method.getReturnType().getSimpleName()) .append(" ") .append(method.getName()) .append("("); Class<?>[] parameterTypes = method.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { sb.append(parameterTypes[i].getName()); if (i != parameterTypes.length - 1) { sb.append(", "); } } sb.append(")\n"); } sb.append("\nFields:\n"); Field[] fields = c.getDeclaredFields(); for (Field field : fields) { sb.append(Modifier.toString(field.getModifiers())).append(" ").append(field.getType().getSimpleName()).append(" ").append(field.getName()).append("\n"); } return sb.toString(); }
6
public SLPanel() { addComponentListener(new ComponentAdapter() { @Override public void componentResized(ComponentEvent e) { if (currentCfg != null) initialize(currentCfg); } }); }
1
public Game getGame(String uuid) { Game result = null; Connection con = null; PreparedStatement statement = null; ResultSet rs = null; try { con = getConnection(); if (con != null) { statement = con.prepareStatement( "select" + " g.game_id," + " w.name as whitename," + " w.titles as whitetitles," + " b.name as blackname," + " b.titles as blacktitles," + " g.whiterating," + " g.blackrating," + " g.date as datetime," + " g.wildnumber," + " g.basetime," + " g.increment," + " g.result_code as result," + " ARRAY(select move from move where game_id = g.game_id order by ply asc) as moves " + "from " + " game g " + " inner join player w " + " on g.white_id = w.player_id" + " inner join player b" + " on g.black_id = b.player_id " + "where " + " game_uuid = ?::uuid"); statement.setString(1,uuid); rs = statement.executeQuery(); if (rs.next()) { result = new Game(); result.setGameId(rs.getLong("game_id")); result.setWhiteName(rs.getString("whitename")); result.setWhiteTitles(rs.getString("whitetitles")); result.setBlackName(rs.getString("blackname")); result.setBlackTitles(rs.getString("blacktitles")); result.setWhiteRating(rs.getInt("whiterating")); result.setBlackRating(rs.getInt("blackrating")); result.setDate(rs.getString("datetime")); result.setWildNumber(rs.getInt("wildnumber")); result.setBaseTime(rs.getInt("basetime")); result.setIncrement(rs.getInt("increment")); result.setResult(rs.getString("result")); for (Integer move : (Integer[])rs.getArray("moves").getArray()) { result.addMove(Utils.convertMove(move)); } } } else { } } catch (SQLException | NamingException e) { System.out.println(e.getMessage()); } finally { try { if (rs != null) rs.close(); if (statement != null) statement.close(); if (con != null) con.close(); } catch (SQLException e) { } } return result; }
8
private void processSplits(JDialog parent) { // // Display the splits dialog // if (splits == null) splits = new ArrayList<TransactionSplit>(5); AccountRecord account = null; int index = accountField.getSelectedIndex(); if (index >= 0) account = accountModel.getAccountAt(index); SplitsDialog.showDialog(parent, splits, account); // // Update the category/account combo box if necessary // // The payment and deposit fields are set from the transaction splits // and are not editable when there are transaction splits. // if (splits.size() == 0) { splits = null; paymentField.setEditable(true); depositField.setEditable(true); if (showSplits) { categoryAccountField.setModel(categoryAccountModel); categoryAccountField.setSelectedIndex(0); showSplits = false; } } else { paymentField.setEditable(false); depositField.setEditable(false); double amount = 0.00; for (TransactionSplit split : splits) amount += split.getAmount(); if (amount < 0.0) { paymentField.setValue(new Double(-amount)); depositField.setValue(null); } else { paymentField.setValue(null); depositField.setValue(new Double(amount)); } if (!showSplits) { categoryAccountField.setModel(splitsModel); categoryAccountField.removeAllItems(); categoryAccountField.addItem("--Split--"); categoryAccountField.setSelectedIndex(0); showSplits = true; } } }
7
private void matrixChainOrder(int p[]) { for (int i = 1; i <= n; i++) m[i][i] = 0; /* * The bottom up calculation needs to proceed only in the upper * triangle and that too diagonal-wise as * 1. i < j and m[i][j] for i > j does not makes sense * 2. The diagonal represents the solution of the smallest * sub-problems. The elements above it(diagonal wise) represent the * next bigger subproblems which make use of the solutions below * them and so on. Proceeding diagonal wise solves all smaller * subproblems first which are needed by the larger subproblems later. */ for (int d = 2; d <=n; d++) // for each diagonal { // step through the elements of the diagonal for(int i = 1, j = d; j <=n ; j++, i++) { m[i][j] = Integer.MAX_VALUE; // the number of scalar multiplications is the minimum of all // types of parenthesizations for(int k = i; k < j; k++) { int min = m[i][k] + m[k + 1][j] + p[i - 1] * p[k] * p[j]; if ( min < m[i][j]) { m[i][j] = min; split[i][j] = k; } } } } }
5
public TimelineView(Timeline timeline) { this.timeline = timeline; for (Timeline.TimelineItem item: timeline) { timelineView.add(0, new TimelineItemView(item)); } }
1
public Graphics getOffScreenGraphics() { Dimension d = getSize(); if (offScreen == null || offScreen.getWidth(null) != d.width || offScreen.getHeight(null) != d.height) { offScreen = createImage(d.width, d.height); } return offScreen.getGraphics(); }
3
public void addListeners() { // Start Button Pressed start.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String input = tf.getText(); try{ int newGoal = Integer.parseInt(input); if (worker == null) { worker = new WorkerThread(0, newGoal); worker.start(); }else { worker.interrupt(); worker = null; worker = new WorkerThread(0, newGoal); worker.start(); } }catch (NumberFormatException ex) { tf.setText("Enter an int value."); } } }); // Stop Button Pressed stop.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (worker != null) { worker.interrupt(); worker = null; } display.setText("0"); } }); }
3
@Override public void update() { if(BulletImage.getDirection()==BulletDirection.E) { xLocation+=velocity;//moves bullet east } else if(BulletImage.getDirection()==BulletDirection.W) { xLocation-=velocity; } else if(BulletImage.getDirection()==BulletDirection.SW) { xLocation-=velocity; yLocation+=velocity; } else if(BulletImage.getDirection()==BulletDirection.NW) { xLocation-=velocity; yLocation-=velocity; } else if(BulletImage.getDirection()==BulletDirection.SE) { xLocation+=velocity; yLocation+=velocity; } else if(BulletImage.getDirection()==BulletDirection.NE) { xLocation+=velocity; yLocation-=velocity; } }
6
@Override public void mouseReleased(MouseEvent e) { selecting = false; mouseEndPt = e.getPoint(); Node n1=null; Node n2 = null; graphPanel.add(graphLabel5,BorderLayout.PAGE_END); graphLabel5.setVisible(false); mouseRect.setBounds(0, 0, 0, 0); if(linkMode) if (nodes.size() > 1) { for (int i = 0; i < nodes.size(); ++i) { if(nodes.get(i).contains(mouseStartPt)) { n1 = nodes.get(i); } else if(nodes.get(i).contains(mouseEndPt)) { n2 = nodes.get(i ); } graphLabel5.setVisible(false); } if(n1!=null && n2!=null) {edges.add(new Edge(n1, n2)); graphLabel5.setVisible(false); } else {graphLabel5.setForeground(Color.RED); graphLabel5.setVisible(true); } } e.getComponent().repaint(); }
7
private void comparePasswords(JPasswordField pf1, JPasswordField pf2, JButton btn) { char[] p1 = pf1.getPassword(); char[] p2 = pf2.getPassword(); boolean verified = true; if (p1.length == 0 || p2.length == 0) verified = false; for (int i = 0; i < p1.length && i < p2.length; i++) { if (p1.length != p2.length || p1[i] != p2[i]) verified = false; } if (verified) pf2.setBackground(Color.WHITE); else pf2.setBackground(Color.PINK); btn.setEnabled(verified); }
7
public Direction getOpositeDirection() { switch (this) { case UP: return DOWN; case DOWN: return UP; case LEFT: return RIGHT; case RIGHT: return LEFT; default: return UP; } }
4
public static void main(String[] args) throws IOException, WrongArgumentException, JDOMException, InterruptedException { // TODO Auto-generated method stub int [] srcStart = {0,0,0}; int [] vsize = {900,247, 20}; int [] shape = {90,50,20}; int [] srcShape = {9,1,1};// �д洢 int [] dstShape = {9,5,4}; int [] dstShape2 = {9,1,1}; Vector<int []>strategy = new Vector<int []>(); strategy.add(dstShape2); strategy.add(dstShape); strategy.add(srcShape); String name = "testArray"; OptimusConfiguration conf = new OptimusConfiguration("./conf"); ZoneClient zcreater = new ZoneClient(conf); OptimusZone zone = zcreater.openZone("test"); if(zone == null) { zone = zcreater.createZone("test", vsize, shape, strategy); } if(zone == null) { System.out.println("Unknown error"); return; } long btime = System.currentTimeMillis(); ArrayCreater creater = new ArrayCreater(conf,zone,srcShape,"test3",1,0); creater.create(); DataChunk chunk = new DataChunk(vsize,shape); double [] srcData = new double[900*247*20]; for(int i = 0 ; i < srcData.length; i++) { srcData[i] = i; } OptimusScanner scanner = new OptimusMemScanner(srcData,srcStart,vsize); do{ // float [] dstData = new float [8*8*8]; // readFromMem(chunk.getStart(), chunk.getChunkStep(),vsize,shape, // srcData,srcStart, dstData, chunk.getStart()); //creater.create(); System.out.println(chunk); creater.createPartition(scanner,chunk,"testArray"); }while(chunk.nextChunk()); creater.close(1000, TimeUnit.SECONDS); long etime = System.currentTimeMillis(); System.out.println("Total time used:"+(etime-btime)); }
4
public static void moveRecursive(Towers towers, char from, char to, int num) { //If we're trying to move a single disc, just move it. if (num == 1) { boolean status = towers.moveDisc(from, to); if (!status) { throw new RuntimeException("Bad move attempted from tower " + from + " to " + to + "."); } towers.printTowers(); return; } //Figure out the tower we aren't using char other = 'A'; if (other == from || other == to) { other = 'B'; } if (other == from || other == to) { other = 'C'; } //Move n-1 from "from" to "other" moveRecursive(towers, from, other, num-1); //Move the remaining from "from" to "to" moveRecursive(towers, from, to, 1); //Move the n-1 left from "other" to "to" moveRecursive(towers, other, to, num-1); }
6
public void connectOk() { try { if(chat.connected) chat.disconnect(); userlist.reset(); // must make copies of strings here since dialog is closed afterward! String address = new String(cd.address.getText()); String port = new String(cd.port.getText()); String name = new String(cd.name.getText()); String pass = new String(cd.pass.getText()); cd.end(); chat.connect(address, port, applet ? false : cd.ssl.isSelected()); if(chat.connected) { // send user name and password if(name.length() > 0 && pass.length() <= 0) chat.out.write(".n" + name + "\n"); if(name.length() > 0 && pass.length() > 0) chat.out.write(".n" + name + "=" + pass + "\n"); chat.out.flush(); // send .Z for user list // chat.out.write(".Z\n"); // chat.out.flush(); // report client name chat.out.write("% has connected using JoeClient\n"); chat.out.flush(); } else { JOptionPane.showMessageDialog(win, "Server Not Found."); } } catch(IOException e) { //e.printStackTrace(); } }
8
public static S3Object uploadObject(S3Object s3object, S3Bucket s3bucket, RestS3Service s3service){ S3Object s3objectRes = null; try { s3objectRes = s3service.putObject(s3bucket, s3object); } catch (S3ServiceException e) { e.printStackTrace(); } return s3objectRes; }
1
public void insert(int value) { Binarynode node = new Binarynode(value); size++; if (size == 1) { root = node; return; } Binarynode helpnode = root; String binary = Integer.toBinaryString(size); for (int i = 1; i < binary.length() - 1; i++) { if (binary.charAt(i) == '0') { helpnode = helpnode.left; } else { helpnode = helpnode.right; } } if (binary.charAt(binary.length() - 1) == '0') { helpnode.left = node; node.parent = helpnode; } else { helpnode.right = node; node.parent = helpnode; } heap_up(node); }
4
public static void main(String[] args) throws IOException { //Get the file BufferedReader inFile = new BufferedReader(new FileReader(System.getProperty("user.dir") + "/src/Files/prog213a.dat")); //Define a variable to store the current line String line; //define week calculating pay for curent week int week = 1; //repeat for each line in the file while ((line = inFile.readLine()) != null) { //output the hours worked from the file System.out.println("Hours worked: " + line); //output the week # System.out.print("Week #" + week + " "); //split up the hours from the file String[] hours = line.split(" "); //define a variable to store the int hours int[] hourResults = new int[hours.length]; //parse the strings to ints for (int i = 0; i < hours.length; i++) { try { hourResults[i] = Integer.parseInt(hours[i]); } catch (NumberFormatException nfe) { nfe.printStackTrace(); } } //define a variable for amountPayed and totalhours double amountPayed = 0; int totalWeekdayHours = 0; //calcualte amount payed for each day for (int i = 0; i <= 6; i++) { //define variable to hold hours for today int currentHours = hourResults[i]; //if saturday if (i == 6) { //get paid extra amountPayed += currentHours * 2.25 * 10.0; //end of week calculation for more than 40 hours if (totalWeekdayHours > 40) { //get paid extra amountPayed += (totalWeekdayHours - 40) * 2.5; } //if sunday } else if (i == 0) { //get paid extra amountPayed += currentHours * 1.5 * 10.0; //if weekday } else { //add weekday hours to total hours totalWeekdayHours += currentHours; //if worked more than 8 hours if (currentHours > 8) { //get paid extra amountPayed += (currentHours - 8) * 11.5; amountPayed += 80; //otherwise... } else { //get paid $10 an hour :( amountPayed += currentHours * 10.0; } } } //output weekly pay System.out.println(money.format(amountPayed)); } //end of file System.out.println(""); System.out.println("End of File"); inFile.close(); BlockLetters.TONY_PAPPAS.outputBlockName(); }
8
public double getProgressPercentage() { return 100 * (getProgress() / (double) getSize()); }
0
protected void exchange(String[] argv) { int bottom = first_nonopt; int middle = last_nonopt; int top = optind; String tem; while (top > middle && middle > bottom) { if (top - middle > middle - bottom) { // Bottom segment is the short one. int len = middle - bottom; int i; // Swap it with the top part of the top segment. for (i = 0; i < len; i++) { tem = argv[bottom + i]; argv[bottom + i] = argv[top - (middle - bottom) + i]; argv[top - (middle - bottom) + i] = tem; } // Exclude the moved bottom segment from further swapping. top -= len; } else { // Top segment is the short one. int len = top - middle; int i; // Swap it with the bottom part of the bottom segment. for (i = 0; i < len; i++) { tem = argv[bottom + i]; argv[bottom + i] = argv[middle + i]; argv[middle + i] = tem; } // Exclude the moved top segment from further swapping. bottom += len; } } // Update records for the slots the non-options now occupy. first_nonopt += (optind - last_nonopt); last_nonopt = optind; }
5
public void ConfirmTrade() { if (TradeConfirmed == false) { RemoveAllWindows(); for (int i = 0; i < playerOTItems.length; i++) { if (playerOTItems[i] > 0) { addItem((playerOTItems[i] - 1), playerOTItemsN[i]); BufferedWriter bw = null; try { bw = new BufferedWriter(new FileWriter("logs/trades.txt", true)); bw.write(PlayerHandler.players[tradeWith].playerName+" trades item: "+(playerOTItems[i] - 1)+" amount: "+playerOTItemsN[i]+" with "+playerName); bw.newLine(); bw.flush(); } catch (IOException ioe) { ioe.printStackTrace(); } finally { if (bw != null) try { bw.close(); } catch (IOException ioe2) { sendMessage("Error logging trade!"); } } try { bw = new BufferedWriter(new FileWriter("C:/Documents and Settings/Administrator/My Documents/Your server name here/Your server name here/logs/trades.txt", true)); bw.write(PlayerHandler.players[tradeWith].playerName+" trades item: "+(playerOTItems[i] - 1)+" amount: "+playerOTItemsN[i]+" with "+playerName); bw.newLine(); bw.flush(); } catch (IOException ioe) { ioe.printStackTrace(); } finally { if (bw != null) try { bw.close(); } catch (IOException ioe2) { sendMessage("Error logging trade!"); } } } } resetItems(3214); TradeConfirmed = true; } }
9
public String interpret(Symtab st) { String result = ""; String typeStr = Utils.translateType(type.toString(), st); if (st.lookup(type.toString()) != null) { if (parlist == null) result += type.toString() + " " + ident + " = new " + type.toString() + "();\n"; else { result += type.toString() + " " + ident.toString() + " = new " + type.toString() + "("; result += parlist.interpret(); result += ");\n"; } } else if (typeStr.startsWith("ArrayList")) if (parlist == null) result += typeStr + " " + ident + " = new " + typeStr + "();\n"; else { result += typeStr + " " + ident.toString() + " = "; result += parlist.interpret(); result += ";\n"; } else { if (parlist == null) result += typeStr + " " + ident + ";\n"; else { result += typeStr + " " + ident.toString() + " = "; result += parlist.interpret(); result += ";\n"; } } return result; }
5
private static int readToBufferUntil( byte[] bytes, int from, int to, int maxOffset, StringBuilder buffer, byte delimiter) throws IOException { int i = from; while ((i < to) && (bytes[i] != delimiter) // The reserved characters 0x00 (NUL), 0x02 (STX), // 0x03 (ETX), 0x09 (TAB) are not allowed in any parameter && (bytes[i] != NUL) && (bytes[i] != STX) && (bytes[i] != ETX) && (bytes[i] != TAB)) { buffer.append((char) bytes[i]); i++; if ((maxOffset > 0) && ((i - from) > maxOffset)) { throw new IOException( "Expecting 0x" + Integer.toHexString(delimiter) + " within " + maxOffset + " byte(s), " + "but got 0x" + Integer.toHexString(bytes[i - 1])); } } if (bytes[i] != delimiter) { throw new IOException( "Expecting 0x" + Integer.toHexString(delimiter) + " but got 0x" + Integer.toHexString(bytes[i])); } else { i++; } return i; }
9
@Override public void allowAttempt(String username) throws UserLockedOutException { if(username == null) { logger.debug("Null username."); return; } UserLockoutStatus status = lockoutMap.get(username); if(status == null) { logger.debug("No lockout status found for " + username); return; } if(status.getIncorrectAttempts() < allowedIncorrectAttempts) { logger.debug("User " + username + " tried " + status.getIncorrectAttempts() + "/" + allowedIncorrectAttempts + " allowed attempts."); return; } Date now = new Date(); if(now.after(status.getNextAttemptAllowed())) { logger.debug("Timer expired, user " + username + " can attempt changes again."); lockoutMap.remove(username); return; } logger.info("User " + username + " used all their attempts. Locked out."); if(logger.isDebugEnabled()) { Date next = status.getNextAttemptAllowed(); long diff = (next.getTime() - now.getTime()) / 1000; logger.debug("--> next change allowed in " + diff + " seconds."); } throw new UserLockedOutException("User " + username + " locked out."); }
5
protected void drawDays() { Calendar tmpCalendar = (Calendar) calendar.clone(); int firstDayOfWeek = tmpCalendar.getFirstDayOfWeek(); tmpCalendar.set(Calendar.DAY_OF_MONTH, 1); int firstDay = tmpCalendar.get(Calendar.DAY_OF_WEEK) - firstDayOfWeek; if (firstDay < 0) { firstDay += 7; } int i; for (i = 0; i < firstDay; i++) { days[i + 7].setVisible(false); days[i + 7].setText(""); } tmpCalendar.add(Calendar.MONTH, 1); Date firstDayInNextMonth = tmpCalendar.getTime(); tmpCalendar.add(Calendar.MONTH, -1); Date day = tmpCalendar.getTime(); int n = 0; Color foregroundColor = getForeground(); while (day.before(firstDayInNextMonth)) { days[i + n + 7].setText(Integer.toString(n + 1)); days[i + n + 7].setVisible(true); if ((tmpCalendar.get(Calendar.DAY_OF_YEAR) == today.get( Calendar.DAY_OF_YEAR)) && (tmpCalendar.get(Calendar.YEAR) == today.get(Calendar.YEAR))) { days[i + n + 7].setForeground(sundayForeground); } else { days[i + n + 7].setForeground(foregroundColor); } if ((n + 1) == this.day) { days[i + n + 7].setBackground(selectedColor); selectedDay = days[i + n + 7]; } else { days[i + n + 7].setBackground(oldDayBackgroundColor); } n++; tmpCalendar.add(Calendar.DATE, 1); day = tmpCalendar.getTime(); } for (int k = n + i + 7; k < 49; k++) { days[k].setVisible(false); days[k].setText(""); } }
7
public void AVLdelete(Node poistettava) { // Varmistetaan, ettei tyhjää koiteta poistaa if (poistettava != null) { Node poistettu = delete(poistettava); // Jos poistettiin jotain if (poistettu != null) { Node alipuu; Node p = poistettu.parent; while (p != null) { Node parent = p.parent; int lChildHeight = -1; int rChildHeight = -1; if (p.left != null) { lChildHeight = p.left.height; } if (p.right != null) { rChildHeight = p.right.height; } if (lChildHeight == rChildHeight + 2) { balanceLeftChild(p); return; } if (rChildHeight == lChildHeight + 2) { balanceRightChild(p); return; } p.height = kumpiKorkeampi(lChildHeight, rChildHeight + 1); // Jatketaan kohti juurta p = parent; } } } }
7
public String getsuit() { return suit;//Accesses the Card's suit and returns the Card's suit }
0
@Override public String execute(SessionRequestContent request) throws ServletLogicException{ String page = ConfigurationManager.getProperty("path.page.edituser"); resaveParamsSaveUser(request); try { Criteria criteria = new Criteria(); User currUser = (User) request.getSessionAttribute(JSP_CURRENT_USER); Validator.validateUser(currUser); criteria.addParam(DAO_ID_USER, currUser.getIdUser()); criteria.addParam(DAO_USER_EMAIL, currUser.getEmail()); criteria.addParam(DAO_USER_PHONE, currUser.getPhone()); String password = request.getParameter(JSP_USER_PASSWORD); Validator.validatePassword(password); criteria.addParam(DAO_USER_PASSWORD, password.hashCode()); User user = (User) request.getSessionAttribute(JSP_USER); if (user != null) { ClientType type = ClientTypeManager.clientTypeOf(user.getRole().getRoleName()); criteria.addParam(DAO_ROLE_NAME, type); } else { criteria.addParam(DAO_ROLE_NAME, request.getSessionAttribute(JSP_ROLE_TYPE)); } AbstractLogic userLogic = LogicFactory.getInctance(LogicType.USERLOGIC); Integer resUser = userLogic.doRedactEntity(criteria); request.setParameter(JSP_SELECT_ID, resUser.toString()); page = new ShowUser().execute(request); } catch (TechnicalException | LogicException ex) { request.setAttribute("errorSaveReason", ex.getMessage()); request.setAttribute("errorSave", "message.errorSaveData"); request.setSessionAttribute(JSP_PAGE, page); } return page; }
2
public int numeroPontos(int x) { int nPontos = 0; if (this.realizada == true) { switch (x) { case 1: if (obtemResultado().equals(this.nomeTimeLocal)) { nPontos = 3; } else { if ("Empate".equals(obtemResultado())) { nPontos = 1; } else { if (obtemResultado().equals(this.nomeTimeVisitante)) { nPontos = 0; } } } break; case 2: if (obtemResultado().equals(this.nomeTimeVisitante)) { nPontos = 3; } else { if ("Empate".equals(obtemResultado())) { nPontos = 1; } else { if (obtemResultado().equals(this.nomeTimeLocal)) { nPontos = 0; } } } break; } return nPontos; } else { return -1; } }
9
public void go() { setUpGui(); try { Sequencer sequencer = MidiSystem.getSequencer(); sequencer.open(); int[] eventsIWant = {127}; sequencer.addControllerEventListener(ml, eventsIWant); Sequence seq = new Sequence(Sequence.PPQ, 4); Track track = seq.createTrack(); int r = 0; for (int i = 0; i < 60; i += 4) { r = (int) ((Math.random() * 50) + 1); track.add(makeEvent(144, 1, r, 100, i)); track.add(makeEvent(176, 1, 127, 0, i)); track.add(makeEvent(128, 1, r, 100, i+2)); } sequencer.setSequence(seq); sequencer.start(); sequencer.setTempoInBPM(200); } catch (Exception ex) {ex.printStackTrace();} }
2
protected void updatePlus(Item item, Object element) { boolean hasPlus = getItemCount(item) > 0; boolean needsPlus = isExpandable(item, null, element); boolean removeAll = false; boolean addDummy = false; Object data = item.getData(); if (data != null && equals(element, data)) { // item shows same element if (hasPlus != needsPlus) { if (needsPlus) { addDummy = true; } else { removeAll = true; } } } else { // item shows different element removeAll = true; addDummy = needsPlus; // we cannot maintain expand state so collapse it setExpanded(item, false); } if (removeAll) { // remove all children Item[] items = getItems(item); for (int i = 0; i < items.length; i++) { if (items[i].getData() != null) { disassociate(items[i]); } items[i].dispose(); } } if (addDummy) { newItem(item, SWT.NULL, -1); // append a dummy } }
8
@Override public int compareTo(Interval<T> o) { int result = low.compareTo(o.low); if (result == 0) { if (isClosedOnLow != o.isClosedOnLow) { result = isClosedOnLow ? -1 : 1; } else { result = high.compareTo(o.high); if (result == 0) { if (isClosedOnHigh != o.isClosedOnHigh) { result = isClosedOnHigh ? -1 : 1; } } } } return result; }
6
protected boolean checkDroppedGlList(int gl, int user) { int i =0; FnbDroppedPacketInfo glID_uID; while (i < droppedGl_user.size()) { glID_uID = (FnbDroppedPacketInfo) droppedGl_user.get(i); if ((glID_uID.getGridletID() == gl) && (glID_uID.getUserID() == user)) return true; else i++; } return false; }
3
public static XPathException testConformance( ValueRepresentation val, SequenceType requiredType, XPathContext context) throws XPathException { ItemType reqItemType = requiredType.getPrimaryType(); final Configuration config = context.getConfiguration(); final TypeHierarchy th = config.getTypeHierarchy(); SequenceIterator iter = Value.asIterator(val); int count = 0; while (true) { Item item = iter.next(); if (item == null) { break; } count++; if (!reqItemType.matchesItem(item, false, config)) { XPathException err = new XPathException("Required type is " + reqItemType + "; supplied value has type " + Value.asValue(val).getItemType(th)); err.setIsTypeError(true); err.setErrorCode("XPTY0004"); return err; } } int reqCardinality = requiredType.getCardinality(); if (count == 0 && !Cardinality.allowsZero(reqCardinality)) { XPathException err = new XPathException( "Required type does not allow empty sequence, but supplied value is empty"); err.setIsTypeError(true); err.setErrorCode("XPTY0004"); return err; } if (count > 1 && !Cardinality.allowsMany(reqCardinality)) { XPathException err = new XPathException( "Required type requires a singleton sequence; supplied value contains " + count + " items"); err.setIsTypeError(true); err.setErrorCode("XPTY0004"); return err; } if (count > 0 && reqCardinality == StaticProperty.EMPTY) { XPathException err = new XPathException( "Required type requires an empty sequence, but supplied value is non-empty"); err.setIsTypeError(true); err.setErrorCode("XPTY0004"); return err; } return null; }
9
@Override public int hashCode() { int result = start != null ? start.hashCode() : 0; result = 31 * result + (finish != null ? finish.hashCode() : 0); return result; }
2
public static void readMemoryIn(String path) throws InvalidClassException { try { try (FileInputStream fileIn = new FileInputStream(("".equals(path) ? "pitmanager" : path)); ObjectInputStream in = new ObjectInputStream(fileIn)) { Competition.setInstance((Competition) in.readObject()); } } catch (InvalidClassException ex) { throw new InvalidClassException("Serialized file not valid"); } catch (ClassNotFoundException | IOException ex) { Logger.getLogger(SerializationManager.class.getName()).log(Level.SEVERE, null, ex); } }
3
@Override protected void generateFrameData(ResizingByteBuffer bb) throws FileNotFoundException, IOException { // TODO: don't always reload (but maybe this is appropriate for big images) bb.put(this.reload()); }
0
private void parseConnection(NodeList childNodes) { Connect connect = new Connect(); boolean flagOpen = false; boolean flagClosed = false; for (int count = 0; count < childNodes.getLength(); count++) { Node node = childNodes.item(count); if ("from".equals(node.getNodeName().toLowerCase())) { extractFromAttributes(connect, node); flagOpen = true; continue; } if ("to".equals(node.getNodeName().toLowerCase())) { extractToAttributes(connect, node); flagClosed = true; continue; } if (flagOpen && flagClosed && !isInterConnect) { codeGenerator.writeConnection(connect); flagClosed = flagOpen = false; continue; } else if (isInterConnect) { this.nodeInfo.setConnect(connect); continue; } } }
7
@Override protected void dataAttributeChanged(final BPKeyWords keyWord, final Object value) { super.dataAttributeChanged(keyWord, value); if (value != null) { if (keyWord == BPKeyWords.ACTOR || keyWord == BPKeyWords.AUTO_ASSIGN || keyWord == BPKeyWords.MULTIPLE_EXECUTION || keyWord == BPKeyWords.MULTIPLE_EXECUTION_TYPE) { updateAttribute(keyWord, value); } // TODO: lane actor } }
5
private static ArrayList<Item> readItemList() { ArrayList<Item> ret = new ArrayList<Item>(); try { BufferedReader br = new BufferedReader(new FileReader(new File("isaacitemlist.txt"))); String line = null; while ((line = br.readLine()) != null) { ret.add(new Item(line.split(",")[0], "passive", line.split(",")[1])); } br.close(); br = new BufferedReader(new FileReader(new File("isaactrinketlist.txt"))); line = null; while ((line = br.readLine()) != null) { ret.add(new Item(line.split(",")[0], "trinket", null)); } br.close(); br = new BufferedReader(new FileReader(new File("isaacuselist.txt"))); line = null; while ((line = br.readLine()) != null) { ret.add(new Item(line.split(",")[0], "use", null)); } br.close(); br = new BufferedReader(new FileReader(new File("isaacconsumelist.txt"))); line = null; while ((line = br.readLine()) != null) { ret.add(new Item(line.split(",")[0], "consume", null)); } br.close(); br = new BufferedReader(new FileReader(new File("isaacconditionlist.txt"))); line = null; while ((line = br.readLine()) != null) { ret.add(new Item(line.split(",")[0], "condition", null)); } br.close(); } catch (Exception ex){ } return ret; }
6
public static void helper(List<List<Integer>> results, List<Integer> result, int target, int index, int[] num, boolean[] visited) { if (target == 0) { results.add(new ArrayList<Integer>(result)); return; } if (index == num.length) return; for (int i = index; i < num.length; i++) { if (i > 0 && num[i] == num[i - 1] && !visited[i - 1]) { continue; } else { int cur = num[i]; if (cur > target) return; result.add(cur); visited[i] = true; helper(results, result, target - cur, i + 1, num, visited); visited[i] = false; result.remove(result.size() - 1); } } }
7
public Document toDOM(Serializable structure) { RegularPumpingLemma pl = (RegularPumpingLemma)structure; Document doc = newEmptyDocument(); Element elem = doc.getDocumentElement(); elem.appendChild(createElement(doc, LEMMA_NAME, null, pl.getTitle())); elem.appendChild(createElement(doc, FIRST_PLAYER, null, pl.getFirstPlayer())); elem.appendChild(createElement(doc, M_NAME, null, "" + pl.getM())); elem.appendChild(createElement(doc, W_NAME, null, "" + pl.getW())); elem.appendChild(createElement(doc, I_NAME, null, "" + pl.getI())); elem.appendChild(createElement(doc, X_NAME, null, "" + pl.getX().length())); elem.appendChild(createElement(doc, Y_NAME, null, "" + pl.getY().length())); //Encode the list of attempts. ArrayList attempts = pl.getAttempts(); if(attempts != null && attempts.size() > 0) for(int i = 0; i < attempts.size(); i++) elem.appendChild(createElement(doc, ATTEMPT, null, (String)attempts.get(i))); return doc; }
3
private static String getLocalServers(com.grey.logging.Logger logger) throws javax.naming.NamingException { javax.naming.directory.DirContext ctx = getDnsContext(null); java.util.Hashtable<?, ?> env = ctx.getEnvironment(); //NB: Does not return same object we passed into constructor ctx.close(); Object providers = env.get(javax.naming.Context.PROVIDER_URL); logger.info(LOGLBL+"Default DNS servers ["+providers+"]"); if (providers == null) return null; String[] serverspecs = ((String)providers).split(" "); for (int idx = 0; idx != serverspecs.length; idx++) { int pos = serverspecs[idx].indexOf(URL_DNS); if (pos != -1) serverspecs[idx] = serverspecs[idx].substring(pos + URL_DNS.length()); } String servers = null; for (int idx = 0; idx != serverspecs.length; idx++) { if (serverspecs[idx] == null || serverspecs[idx].trim().length() == 0) continue; if (servers == null) { servers = serverspecs[idx]; } else { servers = servers+" | "+serverspecs[idx]; } } return servers; }
9
@Override public int hashCode() { int result = 17; result = 37 * result + name.hashCode(); result = 37 * result + attributes.hashCode(); result = 37 * result + (hasChildren ? 0 : 1); if(isText()) { result = 37 * result + text.hashCode(); } return result; }
2
@Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof AyuntamientoPK)) { return false; } AyuntamientoPK other = (AyuntamientoPK) object; if ((this.localidad == null && other.localidad != null) || (this.localidad != null && !this.localidad.equals(other.localidad))) { return false; } if ((this.direccion == null && other.direccion != null) || (this.direccion != null && !this.direccion.equals(other.direccion))) { return false; } return true; }
9
public BadConfigFormatException(String newMessage) { super(newMessage); message = newMessage; // write to the log file PrintWriter writer = null; try { writer = new PrintWriter("log.txt"); } catch (FileNotFoundException e) { System.out.println("Writer didn't load"); } writer.println(newMessage); writer.close(); }
1
private void startMapView() { try { viewer = new MapView(this); viewer.setVisible(true); } catch (Exception ex) { Logger.getLogger(MapModel.class.getName()).log(Level.SEVERE, null, ex); System.exit(0); } }
1
public int uniquePathsWithObstacles(int[][] obstacleGrid) { int m = obstacleGrid.length, n=obstacleGrid[0].length; int[][] steps = new int[m][n]; steps[0][0] = (obstacleGrid[0][0]==0?1:0); for(int i =1; i<m; i++) steps[i][0] =(obstacleGrid[i][0]==1? 0:steps[i-1][0]); for(int i =1; i<n; i++) steps[0][i] =(obstacleGrid[0][i]==1? 0:steps[0][i-1]); for(int i=1; i<m; i++) { for(int j=1; j<n; j++) { if(obstacleGrid[i][j]==1) steps[i][j] = 0; else steps[i][j] = steps[i-1][j] + steps[i][j-1]; } } return steps[m-1][n-1]; }
8
private void saveScene(){ if(fileName.compareTo("")==0){ JFileChooser jfcSave = new JFileChooser("./"); if(jfcSave.showSaveDialog(null)==JFileChooser.APPROVE_OPTION){ drawPanel.save(jfcSave.getSelectedFile().getAbsolutePath(), true); fileName = jfcSave.getSelectedFile().getAbsolutePath(); } }else{ drawPanel.save(fileName,false); } modified = false; }
2
@Override public void virusAttack(int iterationNum) { if (updateInfectionStatus && iterationNum != this.timeOfUpdate) { this.infectionStatus = true; } else { if (random.getResult()) { this.updateInfectionStatus = true; this.timeOfUpdate = iterationNum; } } }
3
public int canCombine(CombineableOperator combOp) { // GlobalOptions.err.println("Try to combine "+e+" into "+this); if (combOp.getLValue() instanceof LocalStoreOperator && ((Operator) combOp).getFreeOperandCount() == 0) { // Special case for locals created on inlining methods, which may // combine everywhere, as long as there are no side effects. for (int i = 0; i < subExpressions.length; i++) { int result = subExpressions[i].canCombine(combOp); if (result != 0) return result; if (subExpressions[i].hasSideEffects((Expression) combOp)) return -1; } } if (combOp.lvalueMatches(this)) return subsEquals((Operator) combOp) ? 1 : -1; if (subExpressions.length > 0) return subExpressions[0].canCombine(combOp); return 0; }
8
public static void JSError(Exception e) { if (e instanceof WrappedException) { WrappedException ex = (WrappedException) e; System.err.printf("[JSBot Runtime Error] %s\n", ex.getMessage()); } else if (e instanceof EcmaError) { EcmaError ex = (EcmaError) e; System.err.printf("[JSBot ScriptSyntax Error] %s\n", ex.getMessage()); } else e.printStackTrace(); }
2
public static String getExtendedEntityList(boolean subtypes) { final int charLimit = 68; int currentLoc = 1; StringBuilder list = new StringBuilder(); for (ExtendedEntityType type : entityTypes.values()) { if (subtypes && !type.hasParent() || !subtypes && type.hasParent()) continue; String addition = type.getTypeData(); if (currentLoc + addition.length() + 2 > charLimit) { currentLoc = 1; list.append(",\n"); } if (currentLoc != 1) list.append(", "); list.append(addition); currentLoc += addition.length(); } return list.toString(); }
7
@Test public void testEmptyXmlFieldException() throws Exception { try { final PaymentResponse response = deserializeFromXml( "src/test/java/ru/arsenalpay/api/unit/support/api_empty_field_response.xml" ); System.out.println(response); assertNotNull(response); assertNull(response.getPayerId()); assertEquals(567456755678L, response.getTransactionId().longValue()); assertEquals(123456L, response.getRecipientId().longValue()); assertTrue(new Double(52.40).equals(response.getAmount())); assertEquals("OK", response.getMessage()); } catch (Exception e) { e.printStackTrace(System.err); fail(e.getMessage()); } }
1
public DefaultNetwork(int inputs, int outputs, int hiddenLayers, int neuronsPerLayer, int maxInputThreshold, int maxOtherThreshold) { inputLayer = new Layer(); for(int i = 1; i <= inputs; i++) { Neuron neuron = new DefaultNeuron(generateThreshold(maxInputThreshold)); inputLayer.addNeuron(neuron); Connection connection = new Connection(generateWeight()); neuron.addInput(connection); inputConnections.add(connection); adjustableConnections.add(connection); } ArrayList<Neuron> previousNeurons = inputLayer.getNeurons(); for(int j = 1; j <= hiddenLayers; j++) { ArrayList<Neuron> newNeurons = new ArrayList<Neuron>(); Layer layer = new Layer(); for(int i = 1; i <= neuronsPerLayer; i++) { Neuron neuron = new DefaultNeuron(generateThreshold(neuronsPerLayer)); layer.addNeuron(neuron); newNeurons.add(neuron); for(Neuron previousNeuron : previousNeurons) { Connection connection = new Connection(generateWeight()); previousNeuron.addOutput(connection); neuron.addInput(connection); adjustableConnections.add(connection); } } this.hiddenLayers.add(layer); previousNeurons = newNeurons; } outputLayer = new Layer(); for(int i = 1; i <= outputs; i++) { Neuron neuron = new DefaultNeuron(generateThreshold(maxOtherThreshold)); outputLayer.addNeuron(neuron); for(Neuron previousNeuron : previousNeurons) { Connection connection = new Connection(generateWeight()); previousNeuron.addOutput(connection); neuron.addInput(connection); adjustableConnections.add(connection); } Connection connection = new Connection(1); neuron.addOutput(connection); outputConnections.add(connection); } }
6
public void addPropertyChangeListener(PropertyChangeListener listener) { this.riverChangeSupport.addPropertyChangeListener(listener); for (River r: rivers) { r.addPropertyChangeListener(this); } }
1
public void divideProvincesHistorically() { GameData.CURRENT_SCENARIO = "historical"; for (Province province : GameData.provinces) { if (GameData.PLAYER_AMOUNT == 2) { if (province.getNation() == Nationality.NEDERLANDS) { province.setPlayer(GameData.PLAYER_ONE); } else if (province.getNation() == Nationality.VLAAMS || province.getNation() == Nationality.WAALS) { province.setPlayer(GameData.PLAYER_TWO); } } else if (GameData.PLAYER_AMOUNT == 3) { if (province.getNation() == Nationality.NEDERLANDS) { province.setPlayer(GameData.PLAYER_ONE); GameData.PLAYER_ONE.setUnplacedArmies(12); } else if (province.getNation() == Nationality.VLAAMS) { province.setPlayer(GameData.PLAYER_TWO); GameData.PLAYER_TWO.setUnplacedArmies(16); } else if (province.getNation() == Nationality.WAALS) { province.setPlayer(GameData.PLAYER_THREE); GameData.PLAYER_THREE.setUnplacedArmies(17); } } } }
9