method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
66d0b942-950c-4a76-bf43-2c677bea67e5
9
private void init() { if (initializeConnection && !outputStreamSet) { if (serverAddress == null || port < 0 || protocol == null) { throw new IllegalStateException("Invalid connection parameters. The port, server address and protocol must be set."); } initializeConnection = false; final OutputStream out; // Check the sockets try { if (protocol == Protocol.TCP) { out = new TcpOutputStream(serverAddress, port, blockOnReconnect); } else if (protocol == Protocol.UDP) { out = new UdpOutputStream(serverAddress, port); } else if (protocol == Protocol.SSL_TCP) { out = new SslTcpOutputStream(serverAddress, port, blockOnReconnect); } else { throw new IllegalStateException("Invalid protocol: " + protocol); } setOutputStream(out, false); } catch (IOException e) { throw new IllegalStateException("Could not set " + protocol + " output stream.", e); } } }
4c724f6f-fc03-470c-96d1-6d3822f9d237
1
public void decreaseLife(int value){ life_delay -= value; if(life_delay <= 0){ life -= 1; life_delay += 100; } }
d8fec382-3492-4a8a-8c5a-976cc664e52d
8
private int pull(ByteBuffer dst) throws IOException { inStream.checkNoWait(5); //if (!inStream.checkNoWait(5)) { // return 0; //} byte[] header = new byte[5]; inStream.readBytes(header, 0, 5); // Reference: http://publib.boulder.ibm.com/infocenter/tpfhelp/current/index.jsp?topic=%2Fcom.ibm.ztpf-ztpfdf.doc_put.cur%2Fgtps5%2Fs5rcd.html int sslRecordType = header[0] & 0xFF; int sslVersion = header[1] & 0xFF; int sslDataLength = (int)((header[3] << 8) | (header[4] & 0xFF)); if (sslRecordType < 20 || sslRecordType > 23 || sslVersion != 3 || sslDataLength == 0) { // Not SSL v3 or TLS. Could be SSL v2 or bad data // Reference: http://www.homeport.org/~adam/ssl.html // and the SSL v2 protocol specification int headerBytes; if ((header[0] & 0x80) != 0x80) { headerBytes = 2; sslDataLength = (int)(((header[0] & 0x7f) << 8) | header[1]); } else { headerBytes = 3; sslDataLength = (int)(((header[0] & 0x3f) << 8) | header[1]); } // In SSL v2, the version is part of the handshake sslVersion = header[headerBytes + 1] & 0xFF; if (sslVersion < 2 || sslVersion > 3 || sslDataLength == 0) throw new ErrorException("Not an SSL/TLS record"); // The number of bytes left to read sslDataLength -= (5 - headerBytes); } assert sslDataLength > 0; byte[] buf = new byte[sslDataLength]; inStream.readBytes(buf, 0, sslDataLength); dst.put(header); dst.put(buf); return sslDataLength; }
2d1e3c5d-3a9b-45fb-aa41-eff888bcfd57
4
@EventHandler(priority = EventPriority.MONITOR) // use MONITOR because we're not changing anything. public void onDeath(PlayerDeathEvent event) { Player p = event.getEntity().getKiller(); if (p == null) return; if (killCooldown.checkCoolAndRemove(p.getUniqueId(), cooldownTime)) { this.kills.remove(p.getUniqueId()); return; } int counter = 1; if (!kills.containsKey(p.getUniqueId())) kills.put(p.getUniqueId(), counter); counter = kills.get(p.getUniqueId()); if (killMessages.containsKey(counter)) { String message = this.messageFormat.replaceAll("%player", p.getDisplayName()); message = message.replaceAll("%kill", this.killMessages.get(counter)); Bukkit.broadcastMessage(this.prefix + message); } }
b56a56ed-bc04-47f8-9d25-43ba5b93d62d
8
public String [] getOptions() { String [] options = new String [21]; int current = 0; options[current++] = "-L"; options[current++] = "" + getLearningRate(); options[current++] = "-M"; options[current++] = "" + getMomentum(); options[current++] = "-N"; options[current++] = "" + getTrainingTime(); options[current++] = "-V"; options[current++] = "" +getValidationSetSize(); options[current++] = "-S"; options[current++] = "" + getSeed(); options[current++] = "-E"; options[current++] =""+getValidationThreshold(); options[current++] = "-H"; options[current++] = getHiddenLayers(); if (getGUI()) { options[current++] = "-G"; } if (!getAutoBuild()) { options[current++] = "-A"; } if (!getNominalToBinaryFilter()) { options[current++] = "-B"; } if (!getNormalizeNumericClass()) { options[current++] = "-C"; } if (!getNormalizeAttributes()) { options[current++] = "-I"; } if (!getReset()) { options[current++] = "-R"; } if (getDecay()) { options[current++] = "-D"; } while (current < options.length) { options[current++] = ""; } return options; }
68edff63-f750-43a6-ac27-43c229414da9
1
@Override public int read() throws IOException { waitForCurrentByteBuffer(); if (reachedEndOfStream()) { return -1; } byte b = currentByteBuffer[currentBufferPosition]; currentBufferPosition++; overallBytesConsumed++; return b & 0xFF; }
c42fa5b4-167d-400e-9443-213c9e5e05bb
3
@Override public void run() { // TODO Auto-generated method stub int i=0; while(!stop){ System.out.println("Value of i: "+i); if(suspend){ synchronized (this) { System.out.println("This thread is going to be suspend..."); try { wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } i++; } }
ceea57c4-3760-4d27-aaa4-1b12c2c89562
4
public static void loadWorlds() { if (containsLoadedWorlds() && ChristmasCrashers.isDebugModeEnabled()) System.out.println("[Warning] LoadWorldsTask is overwriting one or more currently loaded worlds."); for (int i = 0; i < 5; i++) { if (worlds[i] == null) worlds[i] = new World(i); } new Thread(new LoadWorldsTask(worlds)).start(); }
16e76952-53cf-4dd5-a82d-2b95b64ed36b
4
public void swap(GNode node1,GNode node2){ GNode[] children; GNode parent; int size1,size2,dsize; parent=node1.parent; if (parent==null){ root=node2; }else{ children=parent.children; size1=node1.size; size2=node2.size; for (int i=0;i<children.length;i++){ GNode child=children[i]; if (child!=node1) continue; children[i]=node2; } dsize=size2-size1; while(parent!=null){ parent.size+=dsize; parent=parent.parent; } } }
1ff3908c-b48c-4a9f-86d0-ede350992c01
2
public boolean isEnabled() { return comp.isEnabled() && comp.getSelectedText()!=null; }
b1cbce71-645e-4201-b3a4-9e278ba3fbc9
9
static private void jj_add_error_token(int kind, int pos) { if (pos >= 100) return; if (pos == jj_endpos + 1) { jj_lasttokens[jj_endpos++] = kind; } else if (jj_endpos != 0) { jj_expentry = new int[jj_endpos]; for (int i = 0; i < jj_endpos; i++) { jj_expentry[i] = jj_lasttokens[i]; } jj_entries_loop: for (java.util.Iterator it = jj_expentries.iterator(); it.hasNext();) { int[] oldentry = (int[])(it.next()); if (oldentry.length == jj_expentry.length) { for (int i = 0; i < jj_expentry.length; i++) { if (oldentry[i] != jj_expentry[i]) { continue jj_entries_loop; } } jj_expentries.add(jj_expentry); break jj_entries_loop; } } if (pos != 0) jj_lasttokens[(jj_endpos = pos) - 1] = kind; } }
8025f002-35b7-4dc0-8c1d-d20f6d0e33a0
1
public int getPort() { return (isAValidPortNumber()) ? Integer.parseInt(args[1]) : Constants.DEFAULT_PORT; }
a4c3f1e9-5f80-437c-a64f-6cc0548172c5
1
public Object invokeConstructor(Reference ref, Object[] params) throws InterpreterException, InvocationTargetException { if (isWhite(ref)) return super.invokeConstructor(ref, params); throw new InterpreterException("Creating new Object " + ref + "."); }
713a3a10-3a7d-46fb-8a96-83d2baf7e3c7
2
private boolean topLeftCorner(int particle, int cubeRoot) { for(int i = 1; i < cubeRoot + 1; i++){ if(particle == i * cubeRoot * cubeRoot - cubeRoot){ return true; } } return false; }
e012c63c-4044-48ce-ae4c-4c28d0287245
1
private static Move_Two processInput(String xmlString) { //goal is to convert XML representation, embedded //in xmlString, to instance of move object. Ideally //this could be done auto-magically, but these technologies //are heavyweight and not particularly robust. A nice //compromise is to use a generic tree parsing methodology. //such exists for XML -- it is called DOM. DOM is mapped //to many languages and is robust and simple (if a bit //of a hack). JDOM is superior but not as uniformly adopted. //first goal is to yank these values out of XML with minimal effort int moveLocation; String color; int playerID; //parse XML into DOM tree //getting parsers is longwinded but straightforward try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); //once you have parse just call parse. to parse a string vs. //a File requires using an InputSource. In any case result is //a DOM tree -- ie an instance of org.w3c.dom.Document Document document = builder.parse(new InputSource(new StringReader(xmlString))); //must invoke XML validator here from java. It is a major advantage //of using XML //assuming validated we continue to parse the data ... //always start by getting root element Element root = document.getDocumentElement(); //get the value of the id attribute playerID = Integer.parseInt(root.getAttribute("id")); Element locElement = (Element) document.getElementsByTagName("location").item(0); Element colorElement = (Element) document.getElementsByTagName("color").item(0); moveLocation = Integer.parseInt(locElement.getFirstChild().getNodeValue()); color = colorElement.getFirstChild().getNodeValue(); Move_Two moveTwo = new Move_Two(playerID, color, moveLocation); return moveTwo; } catch (Exception e) { System.out.print(e); return null; } }
964667a0-4a1c-41bc-9f92-81d99fcf22cc
7
public static Object conver(String str,Class type){ if(JSTRING.equalsIgnoreCase(type.getName())){ return str; }else if(JINTEGER.equalsIgnoreCase(type.getName())){ return stoInteger(str); }else if(JDATE.equalsIgnoreCase(type.getName())){ return stoDate(str); }else if(JDOUBLE.equalsIgnoreCase(type.getName())){ return stoDouble(str); }else if(JBOOLEAN.equalsIgnoreCase(type.getName())){ return stoBoolean(str); }else if(JLONG.equalsIgnoreCase(type.getName())){ return stoLong(str); }else if(JSHORT.equalsIgnoreCase(type.getName())){ return stoShort(str); } return str; }
2ed31279-9d33-4f05-86e6-f751580d0d12
1
public void setContinuable(boolean b) { final CycSymbol value = b ? CycObjectFactory.t : CycObjectFactory.nil; put(CONTINUABLE, value); }
77961cd8-8f1b-4c4b-8172-0244a62003ee
1
private void onComplete(ActionEvent event){ for (ActionListener listener : completeListeners){ listener.actionPerformed(event); } }
5d04d919-9cf1-4e96-8306-db4e7576664e
8
private boolean cargarDatosProd(Articulo art) { boolean ret = true; try { String codigo = TratamientoString.eliminarTildes(articuloGui.getCodigo().getText()); art.set("codigo", codigo); } catch (ClassCastException e) { ret = false; JOptionPane.showMessageDialog(articuloGui, "Error en el codigo", "Error!", JOptionPane.ERROR_MESSAGE); } try { String marca = TratamientoString.eliminarTildes(articuloGui.getMarca().getText()); art.set("marca", marca); } catch (ClassCastException e) { ret = false; JOptionPane.showMessageDialog(articuloGui, "Error en la marca", "Error!", JOptionPane.ERROR_MESSAGE); } try { String desc = TratamientoString.eliminarTildes(articuloGui.getDescripcion().getText()); art.set("descripcion", desc); } catch (ClassCastException e) { ret = false; JOptionPane.showMessageDialog(articuloGui, "Error en la descripcion", "Error!", JOptionPane.ERROR_MESSAGE); } try { Double precioCompra = Double.valueOf(TratamientoString.eliminarTildes(articuloGui.getPrecioCompra().getText())); art.set("precio_compra", BigDecimal.valueOf(precioCompra).setScale(2, RoundingMode.CEILING)); } catch (NumberFormatException | ClassCastException e) { ret = false; JOptionPane.showMessageDialog(articuloGui, "Error en precio de compra", "Error!", JOptionPane.ERROR_MESSAGE); } try { Double precioVenta = Double.valueOf(TratamientoString.eliminarTildes(articuloGui.getPrecioVenta().getText())); art.set("precio_venta", BigDecimal.valueOf(precioVenta).setScale(2, RoundingMode.CEILING)); } catch (NumberFormatException | ClassCastException e) { ret = false; JOptionPane.showMessageDialog(articuloGui, "Error en precio de venta", "Error!", JOptionPane.ERROR_MESSAGE); } if (Integer.parseInt(articuloGui.getStock().getValue().toString()) < 0) { JOptionPane.showMessageDialog(articuloGui, "Stock negativo", "Error!", JOptionPane.ERROR_MESSAGE); ret = false; } else { art.set("stock", articuloGui.getStock().getValue()); } if (Integer.parseInt(articuloGui.getStockMinimo().getValue().toString()) < 0) { JOptionPane.showMessageDialog(articuloGui, "Stock minimo negativo", "Error!", JOptionPane.ERROR_MESSAGE); ret = false; } else { art.set("stock_minimo", articuloGui.getStockMinimo().getValue()); } try { String equivFram = TratamientoString.eliminarTildes(articuloGui.getEquivFram().getText()); art.set("equivalencia_fram", equivFram); } catch (ClassCastException e) { ret = false; JOptionPane.showMessageDialog(articuloGui, "Error en equivalencia FRAM", "Error!", JOptionPane.ERROR_MESSAGE); } art.setNombreProv(articuloGui.getProveedores().getSelectedItem().toString()); return ret; }
4299127d-56be-4de9-957a-8f309e255f09
2
public int getInt(String key, int def) { if(fconfig.contains(key)) { return fconfig.getInt(key); } else { fconfig.set(key, def); try { fconfig.save(path); } catch (IOException e) { e.printStackTrace(); } return def; } }
5b441b29-757c-4b71-8b13-2f631bfb3fe1
1
private static void Printgraph() { // TODO Auto-generated method stub System.out.print("\n"); for (int i = 0; i < GraphList.size(); i++) { System.out.print(GraphList.get(i)); System.out.print("\n"); } }
97aeae6b-0d47-4f97-b4c0-a8f15055f1de
4
public void exitParkedState(int departureTime) throws VehicleException { this.departureTime = departureTime; if (isParked() != true) { throw new VehicleException("Vehicle isn't parked."); } else if (isQueued() == true) { throw new VehicleException("Vehicle is queue."); } else if (departureTime < getParkingTime()) { throw new VehicleException( "Cannot leave before the vehicle was able to park."); } else if (vehicleState == "parked") { vehicleState = "unparked"; } }
7ab66dce-46f0-4a48-b5e9-b8de9dda365e
9
public static Double combinedGasLaw(Double p1, Double v1, Double t1, Double p2, Double v2, Double t2) { boolean[] nulls = new boolean[6]; nulls[0] = (p1 == null); nulls[1] = (v1 == null); nulls[2] = (t1 == null); nulls[3] = (p2 == null); nulls[4] = (v2 == null); nulls[5] = (t2 == null); int nullCount = 0; for(int k = 0; k < nulls.length; k++) { if(nulls[k]) nullCount++; } if(nullCount != 1) return null; double result = 0; if(nulls[0]) { // p1 is unknown result = p2*v2*t1/(t2*v1); } else if(nulls[1]) { // v1 is unknown result = p2*v2*t1/(t2*p1); } else if(nulls[2]) { // t1 is unknown result = t2*p1*v1/(p2*v2); } else if(nulls[3]) { // p2 is unknown result = p1*v1*t2/(t2*v1); } else if(nulls[4]) { // v2 is unknown result = p1*v1*t2/(t1*p2); } else if(nulls[5]) { // t2 is unknown result = t1*p2*v2/(p1*v1); } return result; }
9acc1388-a9b9-4579-addc-57afc7a52e9a
7
public void setHeader(File file, String[] header) { if (!file.exists()) { return; } try { String currentLine; StringBuilder config = new StringBuilder(""); BufferedReader reader = new BufferedReader(new FileReader(file)); while ((currentLine = reader.readLine()) != null) { config.append(currentLine + "\n"); } reader.close(); config.append("# +----------------------------------------------------+ #\n"); for (String line : header) { if (line.length() > 50) { continue; } int lenght = (50 - line.length()) / 2; StringBuilder finalLine = new StringBuilder(line); for (int i = 0; i < lenght; i++) { finalLine.append(" "); finalLine.reverse(); finalLine.append(" "); finalLine.reverse(); } if (line.length() % 2 != 0) { finalLine.append(" "); } config.append("# < " + finalLine.toString() + " > #\n"); } config.append("# +----------------------------------------------------+ #"); BufferedWriter writer = new BufferedWriter(new FileWriter(file)); writer.write(this.prepareConfigString(config.toString())); writer.flush(); writer.close(); } catch (IOException e) { e.printStackTrace(); } }
c015a3de-654d-4d5e-91ce-6a387a6b0ca3
8
public static List<Vertex> aStar(Graph graph, Vertex start, Vertex goal, Integer[] h) { List<Vertex> vertices = graph.vertices(); List<Vertex> openSet = new Vector<Vertex>(); List<Vertex> closedSet = new Vector<Vertex>(); start.setEstimation(h[(start.getO()-1)]); start.setCost(0); openSet.add(start); while (!openSet.isEmpty()) { //select the goal in openset with min estimated score int min = Integer.MAX_VALUE; Vertex minVertex = null; for (Vertex v : openSet) { if (v.getEstimation()<min) { min = v.getEstimation(); minVertex = v; } } minVertex.setVisited(true); openSet.remove(minVertex); closedSet.add(minVertex); System.out.println("*** Selected vertex "+minVertex.getO()); System.out.println("** vertex "+minVertex.getO()+ "has cost "+minVertex.getCost()+" and estimation "+minVertex.getEstimation()); //calculate f (estimation) List<Edge> incidendEdges = graph.incidendEdges(minVertex); for (Edge e : incidendEdges) { Vertex opposite = graph.opposite(minVertex, e); if (closedSet.contains(opposite)) { continue; } int distance = minVertex.getCost() + e.getO(); boolean tentativeIsBetter; System.out.println("considering vertex "+opposite.getO()+", distance is "+distance); if (!openSet.contains(opposite)) { openSet.add(opposite); System.out.println("vertex "+opposite.getO()+" is added to openset."); tentativeIsBetter = true; } else if (distance < opposite.getCost()) { tentativeIsBetter=true; } else { tentativeIsBetter=false; } if (tentativeIsBetter) { opposite.setCost(distance); opposite.setEstimation(distance + h[(opposite.getO()-1)]); System.out.println("(updated)vertex "+opposite.getO()+ "has cost "+opposite.getCost()+" and estimation "+opposite.getEstimation()); } } } return vertices; }
4347ab0d-d55b-4869-8021-fab91b531a44
1
private static void reset() { deck = new Deck(); for (int i = 0; i < 2; i++) { hands[i] = new HandQueue(); stacks[i] = new WarStack(); } gameOver = false; }
6fa74663-13b3-4df7-9f38-9a07be4ff0c8
1
Function<String, Object> getInjectionContext(String fieldName, Object value) { return new Function<String, Object>() { @Override public Object apply(String key) { if (fieldName.equalsIgnoreCase(key)) { return value; } return null; } }; }
e5efe97b-9ed5-4288-8c6c-fa6cddcf6a23
7
public void Move(int row, int col){ if ((row >= size)|| (col >= size)) return; if (sum >= minimalSum) return; if ((row != size-1)||(col != size-1)) { for (int i=0;i<=1;i++) { sum = sum + matrix[row][col]; Move(row + moveRow[i], col + moveCol[i]); sum = sum - matrix[row][col]; } } else{ if (sum < minimalSum){ minimalSum = sum; System.out.println("" + minimalSum); } } }
cc86d723-3c2b-481a-a47d-7ceb4c0cb3a8
7
@EventHandler public void click(InventoryClickEvent event) { Player p = (Player) event.getWhoClicked(); Inventory inv = event.getInventory(); String name = inv.getTitle(); if(name.equals(title) && event.getRawSlot()!= -999) { event.setCancelled(true); ItemStack item = event.getCurrentItem()!= null ? event.getCurrentItem() : event.getCursor()!= null ? event.getCursor() : inv.getItem(event.getRawSlot()); if(item.getType()== Material.MAGMA_CREAM) { p.closeInventory(); return; } String gamename = ChatColor.stripColor(item.getItemMeta().getDisplayName().split(" ")[0]); Game game = GameManager.getGame(gamename); if(event.isRightClick()) { p.performCommand("ha join " + game.getName()); } else if(event.isLeftClick()) { game.listPlayers(p); } } }
4c602150-f3ce-4225-be22-d62acef12662
6
public boolean getBoolean(int index) throws JSONException { Object object = this.get(index); if (object.equals(Boolean.FALSE) || (object instanceof String && ((String)object).equalsIgnoreCase("false"))) { return false; } else if (object.equals(Boolean.TRUE) || (object instanceof String && ((String)object).equalsIgnoreCase("true"))) { return true; } throw new JSONException("JSONArray[" + index + "] is not a boolean."); }
9e9165a6-a7c8-4627-b451-cbe450f5a692
7
@Override public AbstractStochasticLotSizingSolution solve( AbstractStochasticLotSizingProblem problem) { //First created the DP wrappers around the periods AbstractLotSizingPeriod[] originalPeriods = problem.getPeriods(); DPBackwardRecursionPeriod[] periods = new DPBackwardRecursionPeriod[originalPeriods.length+1]; //Create empty wrappers for (int i = 0; i < originalPeriods.length; i++) { periods[i] = new DPBackwardRecursionPeriod(originalPeriods[i]); } //Add the dummy period at the end periods[periods.length-1] = DPBackwardRecursionPeriod.getDummyPeriod(); //Add the decisions for (int i = 0; i < periods.length-1; i++) { for (int j = i+1; j < periods.length; j++){ try { periods[i].possibleDecisions.add(getDecision(periods, i, j, problem.getServiceLevel())); } catch (ConvolutionNotDefinedException e) { throw new RuntimeException("The demand distributions you have chosen could not be convoluted efficiently. Maybe try using normal distributions?"); } } } //Solve the problem via backward recursion. Skip the dummy period. for (int i = periods.length-2; i >= 0; i--){ try { periods[i].solve(); } catch (SolvingInitialisiationException e) { throw new RuntimeException("The static uncertainty solver tried to solve an uninitialised period. This is a bug and should not happen"); } catch (WrongOptimisationOrderException e) { throw new RuntimeException("The static uncertainty solver tried to solve the periods in the wrong order. This is a bug and should not happen"); } } return new LotsizingDPSolution(periods, getAmoutVariableName()); }
fc470d3b-ac72-49c5-ab9a-7339d7fef30b
7
@Override public boolean equals( Object o ) { if ( this == o ) return true; if ( o == null || getClass() != o.getClass() ) return false; Node node = (Node) o; if ( children != null ? !children.equals( node.children ) : node.children != null ) return false; if ( valueToken != null ? !valueToken.equals( node.valueToken) : node.valueToken != null ) return false; return true; }
072b86e7-b57c-474e-aefc-af27ce78c421
9
private static void writeFile(Statement findDupStmt,String sqlquery, String fileName, boolean printTitles) throws SQLException, IOException { ResultSet rs = findDupStmt.executeQuery(sqlquery); ResultSetMetaData rsmd = rs.getMetaData(); FileWriter fileWriter = new FileWriter(fileName, false); PrintWriter out = new PrintWriter(fileWriter, true); String line = ""; if (printTitles) { line = rsmd.getColumnName(1); for (int i = 2; i == rsmd.getColumnCount(); i++) { line = line + "," + rsmd.getColumnName(i); } out.println(line); line = ""; } SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); while (rs.next()) { for (int i = 1; i <= rsmd.getColumnCount(); i++) { try { if (i == 1) { line = rs.getString(i); } else if (rs.getString(i).equals("null")){ line = line + ","; } else if (i==3 || i==4){ line = line + "," + sdf.format(new Date(rs.getDate(i).getTime()+3600*24*2*1000)); } else { line = line + "," + rs.getString(i); } } catch (NullPointerException e) { line = line + ","; } } line = line + ","; out.println(line); line = ""; } out.close(); fileWriter.close(); }
02a9660d-5509-40b0-877a-505c5f5fb287
2
public double getDouble(int index) { Object value = get(index); try { return value instanceof Number ? ((Number) value).doubleValue() : Double.valueOf((String) value).doubleValue(); } catch (Exception exception) { return 0; } }
78978b01-4145-479c-bec1-da63e5948785
6
public Page page() throws IOException { if (eos) return (null); Page page = new Page(); while (true) { int ret = sync.pageout(page); if (ret < 0) throw (new OggException()); /* ? */ if (ret == 1) { if (page.eos() != 0) eos = true; return (page); } int off = sync.buffer(4096); int len = in.read(sync.data, off, 4096); if (len < 0) return (null); sync.wrote(len); } }
16385e92-2fd5-4b90-b575-4d70d7187337
7
private static int doCreateFile(byte pathName[]) { //Check if file name length is > 32. if (pathName.length > 32) { doOutput("Kernel: User error: File name too long!\n"); return -1; } //A 1 block byte array that will hold the free map byte freeMap[] = new byte[filesys.getBlockSizeOfDisk()]; //Read block 0 into freeMap filesys.getDisk().read(0, freeMap); //Check if the file specified by pathName already exists. String pathNameString = new String(pathName); for (int i = 1; i < 100; i++) { if (freeMap[i] == '1' && pathNameString.equals(filesys.getFileTable()[i].trim())) { doOutput("Kernel: User error: File name already exists at" + "block " + i + "!\n"); return -1; } } //The target block to create the file to. int targetBlock = 1; //Search freeMap for the next 0, which will be the target block. for (int i = 1; i < filesys.getDisk().DISK_SIZE; i++) { if (freeMap[i] == '0') { targetBlock = i; break; } } //Byte array that will hold the path name and file contents. byte pathAndContents[] = new byte[filesys.getBlockSizeOfDisk()]; //Copy path name to pathAndContents arraycopy(pathName, 0, pathAndContents, 0, pathName.length); //Write path and contents to the target block. filesys.getDisk().write(targetBlock, pathAndContents); //Update the free map at targetBlock indicating that block is occupied. freeMap[targetBlock] = '1'; //Write free map back to block 0 of the disk. filesys.getDisk().write(0, freeMap); //Set the file system's fileTable at targetBlock to the file name so //we can look it up and other methods can use it. filesys.getFileTable()[targetBlock] = new String(pathName); //Indicate that file was created successfully. doOutput("Kernel: Created file "); for (int i = 0; i < pathName.length; i++) { doOutput((char) pathName[i] + ""); } doOutput(" at block " + targetBlock + ". \n"); return 0; }
f37a08f2-dff2-4e1b-b9cc-b395685af851
8
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; BaseEntity<?> other = (BaseEntity<?>) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; }
cd94c1c7-cba5-4269-ae7a-ffa07f2f8824
9
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Human human = (Human) o; if (id != null ? !id.equals(human.id) : human.id != null) return false; if (name != null ? !name.equals(human.name) : human.name != null) return false; if (unread != null ? !unread.equals(human.unread) : human.unread != null) return false; return true; }
babdc9ef-3a81-4a58-92d9-b40d5d93b379
6
private Boolean parseBoolean() throws StreamCorruptedException { StringBuffer lenStr = new StringBuffer(); while (input.remaining() > 0) { char ch = input.get(); if (ch == ';') { //indexPlus(1); break; } else { lenStr.append(ch); } } if (lenStr.toString().equals("1")) { lenStr = new StringBuffer().append("true"); } else if (lenStr.toString().equals("0")) { lenStr = new StringBuffer().append("false"); } else { throw new StreamCorruptedException("Boolean has invalid value of " + lenStr); } if (lenStr.length() == 0) { throw new StreamCorruptedException("Boolean has no value"); } Boolean value = null; try { value = Boolean.valueOf(lenStr.toString()); } catch (Throwable e) { throw new StreamCorruptedException("boolean " + lenStr.toString() + " failed to deserialize" ); } objHistory.add(value); return value; }
5c6d78bb-19be-4de2-824c-ec55453b444d
0
public static void setSample(byte[] buffer, int position, short sample) { buffer[position] = (byte)(sample & 0xff); buffer[position+1] = (byte)((sample >> 8) & 0xff); }
8fa0ebb8-b841-4d69-aee3-ed5abee0bb00
8
public void setCurrentValues() { switch (typeOfA) { case Element.ID_NT: rb1A.setSelected(true); break; case Element.ID_PL: rb1B.setSelected(true); break; case Element.ID_WS: rb1C.setSelected(true); break; case Element.ID_CK: rb1D.setSelected(true); break; } switch (typeOfB) { case Element.ID_NT: rb2A.setSelected(true); break; case Element.ID_PL: rb2B.setSelected(true); break; case Element.ID_WS: rb2C.setSelected(true); break; case Element.ID_CK: rb2D.setSelected(true); break; } slider1.setValue((int) distance); slider2.setValue((int) (strength * 100)); }
87c3bc1a-5e55-43d3-a2fb-c56692a36de6
4
public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String line = ""; StringBuilder out = new StringBuilder(); while ((line = in.readLine()) != null && line.length() != 0) { int nSet = Integer.parseInt(line.trim()); for (int t = 0; t < nSet; t++) { String a = in.readLine().trim(); cad = a.toCharArray(); comp = new theComparator(cad); int[] sa = suffixArray(); int[] lcp = lcp(sa); int max = 0; for (int i = 0; i < lcp.length; i++) max = Math.max(max, lcp[i]); out.append(max + "\n"); } } System.out.print(out); }
a498497c-ddf9-46f2-86ea-74748c446a9a
0
public String getEmployee_id() { return employee_id; }
bd941582-a62b-45ae-b4e5-99c91958b123
2
public void test_07() { int nmerSize = 32; String seqStr[] = { "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" // Sequence length = 32 (same as Nmer size) , "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" // Same sequence , "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac" // Added a 'c' at the end , "caaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" // Added a 'c' at the beginning }; // Two almost equal sequences (first one is longer) SuffixIndexerNmer<DnaSequence> seqIndex = new SuffixIndexerNmer<DnaSequence>(new DnaSubsequenceComparator<DnaSequence>(true, 0), nmerSize); for( int i = 0; i < seqStr.length; i++ ) { DnaSequence bseq = new DnaSequence(seqStr[i]); if( !seqIndex.overlap(bseq) ) seqIndex.add(bseq); // Add or overlap } assertEquals("caaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac", seqIndex.get(1).getSequence()); }
d893297e-8d68-4e3b-bc5b-94eca6a6a618
0
public void setReplacement(String replacement) {this.replacement = replacement;}
d4febac9-e014-417f-b2f6-5fbf0b1a316a
7
public boolean onKeyReleaseEvent(Container actor, KeyEvent event) { switch (event.getKeyUnicode()) { case 'a': layout.setUseAnimations(!layout.isUseAnimations()); break; case 'v': layout.setVertical(!layout.isVertical()); break; case 'p': layout.setPackStart(!layout.isPackStart()); break; case 's': int spacing = layout.getSpacing(); if (spacing > 12) spacing = 0; else spacing++; layout.setSpacing(spacing); break; case '+': addActor(); break; case 'q': Clutter.mainQuit(); break; default: return false; } return true; }
627262db-5704-4148-8207-504370dc63a8
2
public int OpenDocument() { //Se il documento non è stato creato if (this._MyDocument == null) return -2; else { //Se il documento non era aperto if (!this._MyDocument.isOpen()) { this._MyDocument.open(); return 1; //Se il documento era aperto } else { return -1; } } }
722d4793-d518-46c7-b56f-4304e3fa9b4a
3
public static void checkAllPositives(String customerId) { // External iteration boolean allPositives = true; for (BankAccount account: christmasBank.getAllAccounts()) if ( account.getCustomerId().equals(customerId) && (account.getBalance().signum() < 0) ) { allPositives = false; break; } System.out.println("All positive balances for " + customerId + " (ext) is " + allPositives); //Internal iteration boolean allPositivesAlt = true; // To be worked out. System.out.println("All positive balances for " + customerId + " (int) is " + allPositivesAlt); }
2baf966c-973a-4527-bb85-bb79aa625e13
1
@Override public int hashCode() { int result = moduleId != null ? moduleId.hashCode() : 0; result = 31 * result + personId; return result; }
5befd128-e747-4e11-abab-fc0219e56a41
6
private void handleIOException( SelectionKey key, WebSocket conn, IOException ex ) { //onWebsocketError( conn, ex );// conn may be null here if( conn != null ) { conn.closeConnection( CloseFrame.ABNORMAL_CLOSE, ex.getMessage() ); } else if( key != null ) { SelectableChannel channel = key.channel(); if( channel != null && channel.isOpen() ) { // this could be the case if the IOException ex is a SSLException try { channel.close(); } catch ( IOException e ) { // there is nothing that must be done here } if( WebSocketImpl.DEBUG ) System.out.println( "Connection closed because of" + ex ); } } }
94c3d0d5-51a8-44a2-b077-71f7475c5cf5
0
public void setjComboBoxVisiteur(JComboBox jComboBoxVisiteur) { this.jComboBoxVisiteur = jComboBoxVisiteur; }
8c01494d-9d83-4715-a9e0-6e1c003ac6df
7
public static String[] textForTag(Element element, String tag) { if (!element.hasChildNodes()) return new String[0]; // Should never happen if we are passed a // valid Element node NodeList tagList = element.getChildNodes(); int tagCount = tagList.getLength(); if (0 == tagCount) // No tags by that name return new String[0]; Vector<String> strings = new Vector<String>(); // Same up all the text // strings for (int j = 0; j < tagCount; ++j) { Node tagNode = tagList.item(j); if (isMatchingNode(tagNode, tag)) { // Look at the children of this tag element. There should be // one or more Text nodes. NodeList list = tagNode.getChildNodes(); int count = list.getLength(); for (int i = 0; i < count; ++i) { Node node = list.item(i); if (node instanceof Text) { String value = trim((Text) node); if (!("".equals(value))) strings.addElement(value); } } // for i... } // if match } // for j... String[] stringArray = new String[strings.size()]; strings.copyInto(stringArray); return stringArray; }
80b3e34d-d4fb-4bf0-b741-bdd978c65d7c
4
@Override public boolean insertHRRecommendations(String text, String positionId) { String sql = INSERT_HR_RECOMMENDATIONS + text + "' where position_id='" + positionId + "'"; Connection connection = new DbConnection().getConnection(); PreparedStatement preparedStatement = null; boolean flag = false; try { preparedStatement = connection.prepareStatement(sql); preparedStatement.executeUpdate(); flag = true; } catch (SQLException e) { m_logger.error(e.getMessage(), e); } finally { try { if (connection != null) connection.close(); if (preparedStatement != null) preparedStatement.close(); } catch (SQLException e) { m_logger.error(e.getMessage(), e); } } return flag; }
f361425f-1723-43ae-a074-b76090314304
8
public void checkLocation(Point location) { if(humanTurn && !game.getHuman().isMadeAccusation()) { int width = this.getWidth()/this.getNumColumns(); int height = this.getHeight()/this.getNumRows(); int row = (int) (location.getY()/height); int column = (int) (location.getX()/width); boolean validTarget = false; for(BoardCell c : this.getTargets()) { if(row == c.getCellRow() && column == c.getCellColumn()) { validTarget = true; if(c.isWalkway()) game.getHuman().updateCurrent('W'); else game.getHuman().updateLastVisited(((RoomCell) c).getRoomInitial()); } } if(validTarget) { target = new Point(column, row); game.getHuman().setLocation(target); humanTurn = false; repaint(); game.setTurnDone(true); if(!game.getHuman().getCurrentRoom().equals("Walkway")) { game.setGuess(new GuessPanel(game)); game.getGuess().setVisible(true); } } else JOptionPane.showMessageDialog(null,"That is not a valid target.", "That is not a valid target.", JOptionPane.ERROR_MESSAGE); } }
4855188f-622e-4704-9008-3a6ee36e77e8
6
private StompFrame constructMessage(StringBuffer incomingMessage) { String fullMessage= incomingMessage.toString(); System.out.println("Server received: "); System.out.println(fullMessage.toString()); int indexOfNewline= fullMessage.indexOf("" + StompFrame.endlineChar); if (indexOfNewline == 0){ fullMessage= fullMessage.substring(StompFrame.lenghtOfEndlineChar); indexOfNewline= fullMessage.indexOf("" + StompFrame.endlineChar); } String header= fullMessage.substring(0, indexOfNewline); if (header.equals("CONNECT")){ return ConnectFrame.factory(fullMessage.substring(indexOfNewline + StompFrame.lenghtOfEndlineChar)); } if (header.equals("SEND")){ return SendFrame.factory(fullMessage.substring(indexOfNewline + StompFrame.lenghtOfEndlineChar)); } if (header.equals("SUBSCRIBE")){ return SubscribeFrame.factory(fullMessage.substring(indexOfNewline + StompFrame.lenghtOfEndlineChar)); } if (header.equals("UNSUBSCRIBE")){ return UnsubscribeFrame.factory(fullMessage.substring(indexOfNewline + StompFrame.lenghtOfEndlineChar)); } if (header.equals("DISCONNECT")){ return DisconnectFrame.factory(fullMessage.substring(indexOfNewline + StompFrame.lenghtOfEndlineChar)); } return ErrorFrame.factory(fullMessage.toString(), "malformed STOMP message"); }
7965e8bf-a688-40e7-8f4c-4dcc9a5f535d
0
public String toString() { return note; }
734230aa-4536-4fe6-a243-1690c04af09a
3
public AnnotationVisitor visitAnnotation(final String desc, final boolean visible) { AnnotationNode an = new AnnotationNode(desc); if (visible) { if (visibleAnnotations == null) { visibleAnnotations = new ArrayList(1); } visibleAnnotations.add(an); } else { if (invisibleAnnotations == null) { invisibleAnnotations = new ArrayList(1); } invisibleAnnotations.add(an); } return an; }
12c694ec-5605-4998-bfb2-9cf1784a22df
4
public static void calculateHeightData(Tile tile, Point[] surrPoints) { Tile[] sTiles = Utils.surroundingPointsToTiles(surrPoints); // Pattern produced by this method matches the encoding. for (int i = 0; i < sTiles.length; i++) { Tile sTile = sTiles[i]; // Only interested in surrounding tiles that are lower. if (tile != null && sTile != null && tile.floor > sTile.floor) { tile.borderFlagTwo = setBit(tile.borderFlagTwo, i, 1); // "i" can be simply used here because the pattern produced by Utils is compatible. } } }
b394d016-8430-4767-82f9-fe5cd70b7fb5
9
@Override public void processarImagem(ArrayList<int[][]> matrizes) { origem = matrizes.get(0); resultado = new int[origem.length][origem[0].length]; int recorde, coordI, coordJ; for (int i=0; i<resultado.length; i++){ for (int j=0; j<resultado[0].length; j++){//para cada pixel recorde = 0; for (int mi=0; mi<dimensao; mi++){ for (int mj=0; mj<dimensao; mj++){//para cada pixel da mascara //pega a coordenada do visinho coordI = i - dimensao/2 + mi; coordJ = j - dimensao/2 + mj; //se o visinho existe if ((coordI >= 0)&&(coordI < resultado.length)&&(coordJ >= 0)&&(coordJ < resultado[0].length)){ if (recorde < origem[coordI][coordJ]){ recorde = origem[coordI][coordJ]; } } } } resultado[i][j] = recorde; } } }
4b8e6fbd-f7cf-4d7a-a7fb-36efd73815e3
6
public static MaterialLib loadFromFile(String filename) { System.out.println("New Material lib : res/models/" + filename); MaterialLib lib = new MaterialLib(); try { BufferedReader reader = new BufferedReader(new FileReader(new File("res/models/" + filename))); String line = ""; String name = ""; String temp = ""; Material m = null; while ((line = reader.readLine()) != null) { if (line.startsWith("newmtl ")) { name = line.split(" ")[1]; System.out.println("New LibMaterial : " + name); if (m == null) { m = new Material(name); } else { lib.getMaterials().add(m); m = new Material(name); } } if (line.startsWith("map_Kd ")) { temp = line.split(" ")[1]; m.setTexture(temp); } } if (m != null) { lib.getMaterials().add(m); } reader.close(); } catch (Exception e) { e.printStackTrace(); } return lib; }
4dbca8b6-464d-4379-b842-f509768b9a40
1
public void insertar(E pData){ Nodo<E> nuevo = new Nodo<>(pData); if (talla == 0 ){ cola = nuevo; } else{ cabeza.previo = nuevo; } nuevo.siguiente = cabeza; nuevo.previo = null; cabeza = nuevo; this.talla++; }
9845c1ea-c16e-4a3c-ad4c-a725cf592212
5
@SuppressWarnings("unchecked") public static <N, T> TKey<N, T> resolve(Class<N> namespace, String name) { if (namespace == null) { throw new IllegalArgumentException("Namespace must not be null."); } if (name == null) { throw new IllegalArgumentException("Name must not be null."); } synchronized (registry) { TKey<N, T> field = new TKey<>(namespace, name, null); TKey<?, ?> featureKey = registry.get(field); if (featureKey != null) { return (TKey<N, T>) featureKey; } } return null; }
b422472e-3ab6-4e5e-bba9-1d62b5d8d72e
6
public void setType(Type otherType) { Type newType = otherType.intersection(type); if (type.equals(newType)) return; if (newType == Type.tError && otherType != Type.tError) { GlobalOptions.err.println("setType: Type error in " + this + ": merging " + type + " and " + otherType); if (parent != null) GlobalOptions.err.println("\tparent is " + parent); if ((GlobalOptions.debuggingFlags & GlobalOptions.DEBUG_TYPES) != 0) Thread.dumpStack(); } type = newType; if (type != Type.tError) updateSubTypes(); }
02400531-f129-4b3e-82c9-51463452d54a
4
public boolean isOptOut() { synchronized (optOutLock) { try { // Reload the metrics file configuration.load(getConfigFile()); } catch (IOException ex) { if (debug) { Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); } return true; } catch (InvalidConfigurationException ex) { if (debug) { Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); } return true; } return configuration.getBoolean("opt-out", false); } }
9fb38275-e3f6-4b1d-8a38-91e088ce4664
1
public void addPatient(PatientDL newPatient){ if (this.nextPatient == null){ this.nextPatient = newPatient; this.nextPatient.lastPatient = this; } else { this.nextPatient.addPatient(newPatient); } }
d47e7395-f557-4a32-96af-69f834917f2d
7
public int principleTerm(int y, int m) { if (y < 1901 || y > 2100) return 0; int index = 0; int ry = y - baseYear + 1; while (ry >= principleTermYear[m - 1][index]) index++; int term = principleTermMap[m - 1][4 * index + ry % 4]; if ((ry == 171) && (m == 3)) term = 21; if ((ry == 181) && (m == 5)) term = 21; return term; }
e434390b-19a0-4fd2-89ba-3d028553d124
4
public static Boolean stoBoolean(String str){ if(str==null){ return false; }else{ if(str.equals("1")){ return true; }else if(str.equals("0")){ return false; }else{ try{ return Boolean.parseBoolean(str); }catch(Exception e){ return null; } } } }
2fbe1f4d-bf62-4264-b86e-24b509d95885
1
void refill() { System.out.println("new Bag"); pointer = 0; DynamicArray<Type> left = new DynamicArray<>(index); for (int n = 6; n >= 0; n--) { int i = rand.nextInt(n+1); tetrominos[n] = left.remove(i); } }
33f52dcb-0291-48f5-ad41-39c0f461187f
1
public boolean jumpMayBeChanged() { return (subBlocks[1].jump != null || subBlocks[1].jumpMayBeChanged()); }
0970f951-4126-4f04-b7d7-4d97218bfbd8
6
public static TreeNode stringToTree(String source) { String seperator = " "; if (source.contains(",")) { seperator = ","; } String[] node = source.split(seperator); if (node.length == 0) { return null; } LinkedList<TreeNode> queue = new LinkedList<TreeNode>(); TreeNode root = new TreeNode(Integer.valueOf(node[0])); queue.add(root); int index = 1; while (index < node.length) { TreeNode cur = queue.poll(); if (!node[index].equals("#")) { TreeNode t = new TreeNode(Integer.valueOf(node[index])); cur.left = t; queue.add(t); } else { cur.left = null; } index++; if (index < node.length) { if (!node[index].equals("#")) { TreeNode t = new TreeNode(Integer.valueOf(node[index])); cur.right = t; queue.add(t); } else { cur.right = null; } } index++; } return root; }
addd48c5-97be-4621-883b-20f8a6253a3f
4
public final boolean check_read () { // Was the value prefetched already? If so, return. int h = queue.front_pos(); if (h != r) return true; // There's no prefetched value, so let us prefetch more values. // Prefetching is to simply retrieve the // pointer from c in atomic fashion. If there are no // items to prefetch, set c to -1 (using compare-and-swap). if (c.compareAndSet (h, -1)) { // nothing to read, h == r must be the same } else { // something to have been written r = c.get(); } // If there are no elements prefetched, exit. // During pipe's lifetime r should never be NULL, however, // it can happen during pipe shutdown when items // are being deallocated. if (h == r || r == -1) return false; // There was at least one value prefetched. return true; }
0df58b5e-ef53-4f40-9104-758a3285f605
5
public boolean checkMoveEligible(Move move) { int row = move.getRow(); int col = move.getColumn(); Player p = move.getPlayer(); if (col < this.getWidth() && row < this.getHeight() && row >= 0 && col >= 0 && board[row][col] == null) { return true; } return false; }
88d05f76-baa3-4176-9b7c-e14817e5a40b
8
public static void main(String[] args) { Scanner cin = new Scanner(System.in); n = cin.nextInt(); for (int i=0; i < n; ++i) { post[i] = cin.nextInt(); } for (int i=0; i < n; ++i) { in[i] = cin.nextInt(); } Queue<Pair> queue = new LinkedList<Pair>(); queue.add(new Pair(0, n-1, 0, n-1)); boolean head = true; while (queue.size() != 0) { Pair p = queue.poll(); if (p.ps > p.pe) continue; if (head) head = false; else System.out.print(" "); System.out.print(post[p.pe]); if (p.ps == p.pe) continue; int i; for (i = p.is; i < p.ie; ++i) { if (in[i] == post[p.pe]){ break; } } queue.add(new Pair(p.ps, p.ps + i - p.is -1, p.is, i - 1)); queue.add(new Pair(p.ps + i - p.is, p.pe - 1, i + 1, p.ie)); } }
4d13e58c-49a0-4135-84f9-35fb2639060f
2
public String constructAMessage(javax.swing.JLabel bpmValueElement, javax.swing.JLabel minValueElement, javax.swing.JLabel maxValueElement, javax.swing.JScrollPane alarmValueElement) { String str=""; int bpm = Integer.parseInt(bpmValueElement.getText()); int min = Integer.parseInt(minValueElement.getText()); int max = Integer.parseInt(maxValueElement.getText()); if( bpm > max || bpm < min) { str = captureTime() + " ALARM TRIGGERED!"; } return str; }
278720b2-2be1-4907-9ea9-ca14dc47e49e
0
public int getDocFrequency() { return docFrequency; }
47bb55bb-8bf4-4e70-ab02-d4ac64de3961
1
@Override public boolean isOK() { return super.isOK() && (coverUrl != null); }
6ff598d1-c51f-4abc-a085-4c8c81be17ce
3
public static Document read() { InputStream in = null; try { in = XmlReader.class.getClassLoader().getResourceAsStream(R.Constants.default_mapping_file); if(in == null ){ in = new FileInputStream(System.getProperty("user.dir")+ File.separator+R.Constants.default_mapping_file); } SAXReader reader = new SAXReader(); return reader.read(in); }catch (FileNotFoundException e){ throw new RuntimeException(R.Constants.default_mapping_file+" was not found!"); } catch (Exception e) { log.error(e); return null; }finally { IOUtils.close(in); } }
13272120-c127-4534-97b5-962af618e131
4
@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.unbanip + " (IP)"); return; } String name = arg1[0]; if (plugin.IPbans.contains(name)) { try { plugin.getUtilities().unbanIP(name); sender.sendMessage(plugin.IP_UNBANNED); return; } catch (SQLException e) { e.printStackTrace(); } } else { sender.sendMessage(plugin.IP_NOT_EXIST); } }
d47eb4f9-87a3-4401-b459-9868607fe22f
0
@Test public void testFindString_fail() throws Exception { Assert.assertNull(_xpath.findString("//div[@id='wrongid']/p/text()")); }
aa69edfe-da7a-48b0-b880-69231e7fa2d1
0
public void display() { System.out.println(); System.out.println("THE HOUSE:"); theHouse.displayCardValues(); System.out.println(); System.out.println("THE PLAYER:"); player.displayCardValues(); System.out.println(); }
19db047e-7e3b-4af0-9387-8f247a226e32
5
private void recursiveMapToString(Map tree, StringBuilder buffer, int deep) { boolean first = true; for (Object key : tree.keySet()) { if (!first) { buffer.append(",\n"); } else { first = false; } for (int t = 0; t < deep; t++) { buffer.append('\t'); } buffer.append('"').append(key).append('"').append(" : "); Object value = tree.get(key); if (value instanceof Map) { buffer.append("{\n"); recursiveMapToString((Map) value, buffer, deep + 1); for (int t = 0; t < deep; t++) { buffer.append('\t'); } buffer.append('}'); } else { value = value.toString().replaceAll("\"", "\'"); buffer.append('"').append(value).append('"'); } } buffer.append('\n'); }
8a7b1f95-e107-443c-a944-fd24cc0b0920
8
private MCandidate createRaw(String exp, String source) { MCandidate mCandidate = new MCandidate(); StringTokenizer st = new StringTokenizer(source, "[]", false); // 기분석 결과 저장 String token = null, infos = ""; String[] arr = null; for( int i = 0; st.hasMoreTokens(); i++ ) { token = st.nextToken(); if( i == 0 ) { arr = token.split("\\+"); for( int j = 0; j < arr.length; j++ ) { // 일반적인 형태소 분석 결과 저장 mCandidate.addMorp(arr[j]); } } else { infos = token; } } // 부가 정보들에 대한 처리 수행 st = new StringTokenizer(infos, "*" + MCandidate.DLMT_ATL + MCandidate.DLMT_BCL + MCandidate.DLMT_HCL + MCandidate.DLMT_CCL + MCandidate.DLMT_ECL + MCandidate.DLMT_PRB, true); while( st.hasMoreTokens() ) { token = st.nextToken(); // 접속 가능한 품사 정보 if( token.equals(MCandidate.DLMT_ATL) ) { token = st.nextToken().trim(); token = token.substring(1, token.length() - 1); mCandidate.addApndblTags(token.split(",")); } // 현재 후보가 가진 접속 조건 else if( token.equals(MCandidate.DLMT_HCL) ) { token = st.nextToken().trim(); token = token.substring(1, token.length() - 1); mCandidate.addHavingConds(token.split(",")); } // 접속 확인 조건 else if( token.equals(MCandidate.DLMT_CCL) ) { token = st.nextToken().trim(); token = token.substring(1, token.length() - 1); mCandidate.addChkConds(token.split(",")); } // 접속 배제 조건 else if( token.equals(MCandidate.DLMT_ECL) ) { token = st.nextToken().trim(); token = token.substring(1, token.length() - 1); mCandidate.addExclusionConds(token.split(",")); } } // 기본 음운, 접속 조건 초기화 mCandidate.initConds(exp); return mCandidate; }
bc148e7d-cbe7-4443-8763-1f80ecb38c47
9
public void postOrder3(Node Root) { if(Root==null) return; this.recoverVisited(Root); Stack<Node> s = new Stack<Node>(); Node cur = Root; while((cur!=null&& cur.visited==0)||!s.isEmpty()) { //左结点访问结束的标志是 pre为空 while(cur!=null && cur.visited==0) { s.push(cur); cur = cur.left; } if(!s.isEmpty()) { cur = s.pop(); if (cur.right!=null && cur.right.visited==0) { s.push(cur); cur = cur.right; } else visit(cur); } } }
2e2d9001-7919-45db-b19f-e7f943fd669d
8
private static void performAnyOverlapmatch(AbstractResultSet goldStandard, AbstractResultSet results,boolean matchType) { int comp; for(Concept gold : goldStandard.concepts) { for(Concept res : results.concepts) { if(matchType) if(!res.conceptType.equals(gold.conceptType)) continue; comp = gold.compare(res); if(comp == Concept.FULL_MATCH || comp == Concept.PARTIAL_MATCH || comp == Concept.OVERLAP) { res.correctlyExtracted = true; if(gold.correctlyExtracted) res.duplicate = true; gold.correctlyExtracted = true; } } } }
c04a55bc-b529-409a-afb8-d00c6a854277
8
@Override public ApiResponse deleteTable(String tableName) throws IllegalArgumentException{ if(connexion == null && path == null) return ApiResponse.MYAPI_NOT_INITIALISE; Statement stat = null; try { if (connect == null || connect.isClosed()) return ApiResponse.DATABASE_NOT_CONNECT; if (tableName == null) throw new IllegalArgumentException("An argument is null."); stat = connect.createStatement(); stat.execute("DROP TABLE IF EXISTS " + tableName); } catch (SQLException e) { e.printStackTrace(); return ApiResponse.ERROR; } finally { if (stat != null) try { stat.close(); } catch (SQLException e) { e.printStackTrace(); return ApiResponse.ERROR; } } return ApiResponse.SUCCESS; }
6fc74c56-210b-4e5b-b0bf-414d7072a977
3
public void setProfile( Profile p ) throws IOException { topScoresPanel.removeAll(); int i = 0; for ( Score s : p.getStats().getTopScores() ) { InputStream stream = null; try { ShipBlueprint ship = DataManager.get().getShip( s.getShipType() ); stream = DataManager.get().getResourceInputStream("img/ship/"+ship.getImg()+"_base.png"); Image img = frame.getScaledImage( stream ); TopScorePanel tsp = new TopScorePanel( ++i, img, s.getShipName(), s.getScore(), s.getSector(), s.getDifficulty() ); topScoresPanel.add( tsp ); } finally { try {if (stream != null) stream.close();} catch (IOException f) {} } } Stats stats = p.getStats(); sessionRecordsPanel.removeAll(); sessionRecordsPanel.addRow("Most Ships Defeated", null, null, stats.getMostShipsDefeated()); sessionRecordsPanel.addRow("Most Beacons Explored", null, null, stats.getMostBeaconsExplored()); sessionRecordsPanel.addRow("Most Scrap Collected", null, null, stats.getMostScrapCollected()); sessionRecordsPanel.addRow("Most Crew Hired", null, null, stats.getMostCrewHired()); sessionRecordsPanel.addFillRow(); crewRecordsPanel.removeAll(); CrewRecord repairCrewRecord = stats.getMostRepairs(); CrewRecord killsCrewRecord = stats.getMostKills(); CrewRecord evasionsCrewRecord = stats.getMostEvasions(); CrewRecord jumpsCrewRecord = stats.getMostJumps(); CrewRecord skillsCrewRecord = stats.getMostSkills(); crewRecordsPanel.addRow("Most Repairs", frame.getCrewIcon(repairCrewRecord.getRace()), repairCrewRecord.getName(), repairCrewRecord.getScore()); crewRecordsPanel.addRow("Most Combat Kills", frame.getCrewIcon(killsCrewRecord.getRace()), killsCrewRecord.getName(), killsCrewRecord.getScore()); crewRecordsPanel.addRow("Most Piloted Evasions", frame.getCrewIcon(evasionsCrewRecord.getRace()), evasionsCrewRecord.getName(), evasionsCrewRecord.getScore()); crewRecordsPanel.addRow("Most Jumps Survived", frame.getCrewIcon(jumpsCrewRecord.getRace()), jumpsCrewRecord.getName(), jumpsCrewRecord.getScore()); crewRecordsPanel.addRow("Most Skill Masteries", frame.getCrewIcon(skillsCrewRecord.getRace()), skillsCrewRecord.getName(), skillsCrewRecord.getScore()); crewRecordsPanel.addFillRow(); totalStatsPanel.removeAll(); totalStatsPanel.addRow("Total Ships Defeated", null, null, stats.getTotalShipsDefeated()); totalStatsPanel.addRow("Total Beacons Explored", null, null, stats.getTotalBeaconsExplored()); totalStatsPanel.addRow("Total Scrap Collected", null, null, stats.getTotalScrapCollected()); totalStatsPanel.addRow("Total Crew Hired", null, null, stats.getTotalCrewHired()); totalStatsPanel.addBlankRow(); totalStatsPanel.addRow("Total Games Played", null, null, stats.getTotalGamesPlayed()); totalStatsPanel.addRow("Total Victories", null, null, stats.getTotalVictories()); totalStatsPanel.addFillRow(); this.repaint(); }
23a1fc14-a776-4270-803a-0b8ca9e8c335
7
public ConfigManager() { availableConfigs = new ArrayList<Map<String,IConfig>>(); Map<String, IConfig> map = null; for( int i = 1; i <= 6; i++ ) { map = new HashMap<String, IConfig>(); switch( i ) { case 1: map.put(SERVLET, JettyConfig.getConfig()); break; case 2: map.put(SERVLET, TomcatConfig.getConfig()); break; case 3: map.put(DATABASE, SQLiteConfig.getConfig()); break; case 4: map.put(DATABASE, MySQLConfig.getConfig()); break; case 5: map.put(DATABASE, PostgreSQLConfig.getConfig()); break; case 6: map.put(DATABASE, OracleConfig.getConfig()); break; } availableConfigs.add(map); } }
42fb1258-47a6-4909-8814-3165cfff4547
3
public static void main(String[] args) { List<Pet> pets = Pets.arrayList(8); ListIterator<Pet> it = pets.listIterator(); while (it.hasNext()) System.out.print(it.next() + ", " + it.nextIndex() + ", " + it.previousIndex() + "; "); System.out.println(); // Backwards: while (it.hasPrevious()) System.out.print(it.previous().id() + " "); System.out.println(); System.out.println(pets); it = pets.listIterator(3); while (it.hasNext()) { it.next(); it.set(Pets.randomPet()); } System.out.println(pets); }
de55d02e-6622-4b6a-b975-734405d4dc97
8
private void attemptSpawn(float dt){ spawnTime-=dt; if(spawnTime<=0 && spawnedObjs.size()<spawnMax ){ if(main.dayTime>=Main.NIGHT_TIME && spawnType==SpawnType.CIVILIAN) spawnType = SpawnType.NIGHTER; else if(main.dayTime<Main.NIGHT_TIME && spawnType==SpawnType.NIGHTER) spawnType = SpawnType.CIVILIAN; Mob e = spawn(x, y); if(e!=null) if(Game.res.getTexture(e.ID)!=null){ e.setGameState(main); main.addObject(e); spawnedObjs.put(e, 0f); } spawnTime = spawnDelay; } }
64768fb0-32b4-43b3-976c-6f7431d23306
5
@Override public void processCommand(String... args) throws SystemCommandException { Role internshipRole = null; if (args.length > 2) try { internshipRole = createNewInternshipRole(); } catch (Exception e) { // IO or ParseException e.printStackTrace(); } else { Integer advertIndex = Integer.parseInt(args[0]); Integer roleIndex = Integer.parseInt(args[1]); internshipRole = facade.selectRole(advertIndex,roleIndex); if (internshipRole == null) try { internshipRole = createNewInternshipRole(); } catch (Exception e) { // IOException or ParseException e.printStackTrace(); } } //Collect supplementary details. try { String managerName = dialogue.getUserInput("Enter manager name."); String managerEmail = dialogue.getUserInput("Enter manager's email address."); facade.notifyAcceptedOffer(internshipRole, managerName, managerEmail); } catch (IOException e) { e.printStackTrace(); } }
94ce50bd-a44f-4cbe-ba31-07ece6e47173
7
@EventHandler public void onInventoryOpen(InventoryOpenEvent event){ //We don't care about players other than the owner if(!event.getPlayer().equals(owner)) return; //We don't care about non-chest interactions if(!event.getInventory().getType().equals(InventoryType.CHEST)) return; if(event.getInventory().getHolder()==null) return; if(!(event.getInventory().getHolder() instanceof Chest)) return; if(!(event.getPlayer() instanceof Player)) return; Chest chest = (Chest) event.getInventory().getHolder(); Player player = (Player) event.getPlayer(); if(!plugin.isStore(chest)) return; if(!plugin.getStoreOwner(chest).equals(player)){ plugin.sendPlayerMessage(player, "You must open one of "+ChatColor.GOLD+"your"+ChatColor.WHITE+" stores to set the trade value of items. Use /rs trade again."); unregister(); event.setCancelled(true); return; } /** * We've opened one of our stores, when it closes, stop listening */ clear = true; plugin.sendPlayerMessage(player, "Click on any of the items in your store with an item on the cursor to set the trade value."); }
416c8e16-25e6-469b-8b02-162345843140
6
public void handleEvents(GameContainer game, StateBasedGame sbg){ Input events = game.getInput(); if(events.isKeyPressed(Keyboard.KEY_RETURN)){ //Ainda estamos escrevendo o nome? if(scores.newEntry){ //PArando de escrever e salvando o atual: scores.setNewScoreName(newName.getText()); newName.deactivate(); //Atualziando o DB: scores.updateDatabase(); //Salvando no arquivo: try { scores.saveCurrentScoreBoard(); } catch (IOException ex) { Logger.getLogger(HighScores.class.getName()).log(Level.SEVERE, null, ex); } }else{ //Novo Jogo: //sbg.enterState(SlotMachineSim.PLAYING, new FadeOutTransition(), new FadeInTransition()); } } if(events.isKeyPressed(Keyboard.KEY_ESCAPE)){ //Ainda estamos escrevendo o nome? if(!scores.newEntry){ //Garantindo que o score foi salvo: try { scores.saveCurrentScoreBoard(); } catch (IOException ex) { Logger.getLogger(HighScores.class.getName()).log(Level.SEVERE, null, ex); } //Saindo do jogo: game.exit(); } } }
c5cf0dca-f58d-4bc7-85de-e99ffcb0d90c
7
public static Integer[] mergeBintoA(Integer[] A, Integer[] B){ //1 3 7 _ _ _ //2 4 5 //1 2 3 4 5 7 //- - - 1 3 7 //1 - - - 3 7 //1 2 //Let us assume the array is init with min value for missing spaces int aLength = A.length; //First we determine where the last element is int lastElementPos = 0; for(int i =0; i<aLength; i++){ if(A[i] == Integer.MIN_VALUE){ lastElementPos = i-1; break; } } //Then we shift the array to the end int count = 0; for(int i = lastElementPos; i>=0; i--){ A[aLength-1 - count] = A[i]; A[i] = Integer.MIN_VALUE; count++; } //printList("Shifted:", A); //Now we can merge int aStart = 0; for(int i=0; i<aLength; i++){ if(A[i] != Integer.MIN_VALUE){ aStart = i; break; } } int bStart = 0, aHead = 0; while(bStart != (B.length) ){ if(A[aStart] < B[bStart]){ A[aHead] = A[aStart]; A[aStart] = Integer.MIN_VALUE; aHead++; aStart++; } else{ A[aHead] = B[bStart]; aHead++; bStart++; } } return A; }
b7adc100-92b1-4481-a60e-e4bce121dff9
2
public void run() { try { DataInputStream in = new DataInputStream( socket.getInputStream() ); port = in.readInt(); int length = in.readInt(); byte[] message = new byte[length]; in.readFully( message, 0, message.length ); DataInputStream data = new DataInputStream( new ByteArrayInputStream( message ) ); String task = data.readUTF(); if ( task.equals( "PlayersTeleportBackLocation" ) ) { TeleportManager.setPlayersTeleportBackLocation( PlayerManager.getPlayer( data.readUTF() ), new Location( getServer( new InetSocketAddress( socket.getInetAddress(), port ) ), data.readUTF(), data.readDouble(), data.readDouble(), data.readDouble() ) ); } data.close(); in.close(); } catch ( IOException e ) { e.printStackTrace(); } }
38e51aca-88e7-4256-9a3d-3f1752c4db07
0
public Matrix(int n,int m) { columns = n; rows = m; matrix = new double[n][m]; }
84432902-5343-466c-9a48-42695e541ba9
0
public static void main(String[] args) { String input; Scanner scan = new Scanner(System.in); System.out.println("Input the word to check if it is a palindrome"); input = scan.nextLine(); System.out.println(checkForPalindrome(input.toLowerCase())); }
1183c11a-a34b-46ec-9258-18b457db5784
5
public static void main(String[] args) { System.out.print("Enter a binary number: "); Scanner scanner = new Scanner(System.in); String binaryNumber = scanner.next(); int decimalNumber = 0; int positionOfLastValue = binaryNumber.length() - 1; for (int i = positionOfLastValue, j = 0; i >= 0 && j<= positionOfLastValue; i--, j++) { if (binaryNumber.charAt(i) == '1') { decimalNumber = decimalNumber + (int)Math.pow(2, j); } else if (binaryNumber.charAt(i) != '1' && binaryNumber.charAt(i) != '0'){ System.out.println("You have entered an invalid binary number"); System.exit(0); } } System.out.println("The decimal number representation of the binary number you entered is " + decimalNumber); }
a2956ef0-0bc1-4ebb-9c60-fb298a0b9d39
2
public String getStatusObjectDescr (Integer ID) { String data = ""; for (int i = 0; i < this.arr_data.size(); i++) { if (ID == this.arr_data.get(i).getID()) { data = this.arr_data.get(i).getDescr(); } } return data; }
dbfd2e77-5223-4172-805c-5075808f9450
5
@Test public void testServerGetQueueTimeoutErrorIndividualHashEx() { LOGGER.log(Level.INFO, "----- STARTING TEST testServerGetQueueTimeoutErrorIndividualHashEx -----"); boolean exception_other = false; String client_hash = ""; try { server2.setUseMessageQueues(true); } catch (TimeoutException e) { exception_other = true; } try { server1.startThread(); } catch (IOException | ServerSocketCloseException | FeatureNotUsedException e) { exception_other = true; } waitListenThreadStart(server1); try { client_hash = server2.addSocket("127.0.0.1", port); } catch (IOException | TimeoutException e) { exception_other = true; } waitSocketThreadAddNotEmpty(server2); waitSocketThreadState(server2, client_hash, SocketThread.CONFIRMED); waitMessageQueueAddNotEmpty(server2); waitMessageQueueState(server2, client_hash, MessageQueue.RUNNING); try { server2.getQueueTimeoutErrorIndividual("TEST"); } catch (HashNotFoundException e) { exception = true; } catch (FeatureNotUsedException | NullException | InvalidArgumentException e) { exception_other = true; } Assert.assertFalse(exception_other, "Caught an unexpected exception"); Assert.assertTrue(exception, "Successfully ran getQueueTimeoutErrorIndividual on server, should have received an exception"); LOGGER.log(Level.INFO, "----- TEST testServerGetQueueTimeoutErrorIndividualHashEx COMPLETED -----"); }
cd4f27c8-71b3-4eb8-b26f-7d53f554d14d
5
public static List<SchemaError> checkBadChars(URL file){ List<SchemaError> errors=new ArrayList<SchemaError>(); if(file!=null){ try { BufferedReader br=new BufferedReader(new InputStreamReader(file.openStream())); String line=br.readLine(); int j=0; while(line!=null){ j++; for(int i=0;i<line.length();i++){ if(line.codePointAt(i)>127){ SchemaError shemaError = (SchemaError)Factory.getFactory().getDataObject(Factory.ObjectTypes.SchemaError); shemaError.setEntityName(file.getFile()); Error error=(Error)Factory.getFactory().getDataObject(Factory.ObjectTypes.Error); error.setErrorType(ErrorType.ERROR); error.setErrorCode("-9999"); error.setMessage("Bad Unicode Character encounted at line number: <br/>"+ j + " Charcter : "+ line.charAt(i)); error.setSuggestion("Remove the bad character as only UTF-8 characters can be parsed, check with XmlSpy.<br/> Line with Error: "+ line); shemaError.setError(error); errors.add(shemaError); } } line=br.readLine(); } } catch (IOException e) { throw new ParserExeption("Error Parsing documents", e); } } return errors; }