method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
3634598d-c458-48af-b24c-8ee50d1abaa7
1
private void setBalance(BigInteger balance) throws IllegalArgumentException { if (! this.canHaveAsBalance(balance)) throw new IllegalArgumentException(); this.balance = balance; }
e16e9c8f-e913-4598-a697-9ff42a28a369
1
public void addVariableToLambdaSet(String variable, Set lambdaSet) { if (!lambdaSet.contains(variable)) lambdaSet.add(variable); }
7f190a8b-3296-4172-869f-166363730fc0
4
public void computePaths(Node source) { this.source = source; PriorityQueue<Pair> nodeQueue = new PriorityQueue<Pair>(); nodeQueue.add(new Pair(0,source)); // System.out.println(source); for(int i = 0; i < distance.length; i++) { distance[i] = INFINITY; pred[i] = -1; } distance[source.getId()] = 0; while (!nodeQueue.isEmpty()) { Pair u = nodeQueue.poll(); for (Edge edge : u.node.getOutEdges()) { Node v = edge.getTo(); if (u.distance + 1 < distance[v.getId()]) { nodeQueue.remove(v); distance[v.getId()] = u.distance + 1; pred[v.getId()] = u.node.getId(); nodeQueue.add(new Pair(u.distance + 1, v)); } } } // System.out.println(Arrays.toString(pred)); }
f40eb8cc-6af1-4b76-a549-060c536781ca
3
private ByteBuffer convertImageData(BufferedImage bufferedImage, Texture tex) { ByteBuffer imageBuffer = null; WritableRaster raster; BufferedImage texImage; int texWidth = 2; int texHeight = 2; // find the closest power of 2 for the width and height // of the produced texture while (texWidth < bufferedImage.getWidth()) { texWidth *= 2; } while (texHeight < bufferedImage.getHeight()) { texHeight *= 2; } tex.setWidth(texWidth); tex.setHeight(texHeight); // create a raster that can be used by OpenGL as a source // for a texture if (bufferedImage.getColorModel().hasAlpha()) { raster = Raster.createInterleavedRaster(DataBuffer.TYPE_BYTE,texWidth,texHeight,4,null); texImage = new BufferedImage(glAlphaColorModel,raster,false,new Hashtable()); } else { raster = Raster.createInterleavedRaster(DataBuffer.TYPE_BYTE,texWidth,texHeight,3,null); texImage = new BufferedImage(glColorModel,raster,false,new Hashtable()); } // copy the source image into the produced image Graphics g = texImage.getGraphics(); g.setColor(new java.awt.Color(0f,0f,0f,0f)); g.fillRect(0,0,texWidth,texHeight); g.drawImage(bufferedImage,0,0,null); // build a byte buffer from the temporary image // that be used by OpenGL to produce a texture. byte[] data = ((DataBufferByte) texImage.getRaster().getDataBuffer()).getData(); imageBuffer = ByteBuffer.allocateDirect(data.length); imageBuffer.order(ByteOrder.nativeOrder()); imageBuffer.put(data, 0, data.length); return imageBuffer; }
507422d8-35ad-4bd8-8c69-94083dea6aa1
5
public static void init() { try { Field[] ff = Images.class.getFields(); for(Field f : ff) { if(f.getType().isAssignableFrom(ImageIcon.class)) f.set(null, createIcon(f.getName() + ".png")); } } catch(SecurityException e) { e.printStackTrace(); } catch(IllegalArgumentException e) { e.printStackTrace(); } catch(IllegalAccessException e) { e.printStackTrace(); } }
6fa37535-8138-47dc-8a65-c5daf5026f1a
2
public void dumpExpression(TabbedPrintWriter writer) throws java.io.IOException { subExpressions[0].dumpExpression(writer, 201); writer.breakOp(); writer.print(" ? "); int subPriority = 0; if (!subExpressions[1].getType().getHint() .isOfType(subExpressions[2].getType())) { writer.startOp(writer.IMPL_PAREN, 2); /* We need a cast here */ writer.print("("); writer.printType(getType().getHint()); writer.print(") "); subPriority = 700; } subExpressions[1].dumpExpression(writer, subPriority); if (subPriority == 700) writer.endOp(); writer.breakOp(); writer.print(" : "); subExpressions[2].dumpExpression(writer, 200); }
0c6c2a67-a8a1-401f-b037-c040813c4019
0
void setFTS(File f){ this.fTS = f; }
f2ae84e6-5720-4079-b00d-1a2efccc80f4
0
@Override public void draw() { System.out.println(" # "); System.out.println(" ### "); System.out.println(" ##### "); System.out.println("#######"); }
a26da6ca-a500-4389-a9b4-7fc8a0fa210d
4
@Override public void mouseClicked(MouseEvent e) { if(e.getSource() == dataList) { try { int index = dataList.locationToIndex(e.getPoint()); Dwarf dwarf = dwarfList.get(index); showDwarfData(dwarf); } catch (BadLocationException ex) { Logger.getLogger(DwarfListWindow.class.getName()).log(Level.SEVERE, null, ex); } } if(e.getSource() == textArea) { Element ele = doc.getCharacterElement(textArea.viewToModel(e.getPoint())); AttributeSet as = ele.getAttributes(); ChildrenLinkListener fla = (ChildrenLinkListener)as.getAttribute("linkact"); if(fla != null) { fla.execute(); } } }
826ac036-642d-4532-aef6-5a9d68b5fe64
3
public void setPlateWidth(double width){ if(width<=0.0D)throw new IllegalArgumentException("The plate width, " + width + ", must be greater than zero"); this.plateWidth = width; if(this.plateSeparation!=-1.0)this.distancesSet = true; if(this.distancesSet)this.calculateDistributedCapacitanceAndInductance(); }
df485160-bfd5-4d35-84c3-4925b6eace43
6
public static String findUser(Map<String, Object> paramMap) throws SQLException{ String userName = paramMap.get("userName")==null ? "" : (String)paramMap.get("userName"); String password = paramMap.get("password")==null ? "" : (String)paramMap.get("password"); BEGIN(); SELECT(User.COLUMNS); FROM(User.TABLE_NAME); if(Validator.isNotNull(userName) && Validator.isNotNull(password)){ WHERE(" (userName" + "='" + userName + "' OR email = '"+userName+"') AND password = '"+password+"'"); }else if (Validator.isNotNull(userName) && Validator.isNull(password)){ WHERE("userName" + "='" + userName + "' OR email = '"+userName+"'"); } return SQL(); }
684be971-2b6e-41b0-bfea-0ddcc0e34544
3
@Override public void run() { ResultSet paperIDSet=getPaperIDSet(); String insert="insert into paperauthorList(paperid,authorlist) values(?,?);"; PreparedStatement statement=null; int count=0; try { SQLconnection connection=new connection().conn(); statement=connection.conn.prepareStatement(insert); while(paperIDSet.next()) { int id=paperIDSet.getInt("paperid"); String author=getAuthor(connection,id); statement.setInt(1, id); statement.setString(2, author); statement.addBatch(); count++; if(count%1000==0) { statement.executeBatch(); statement.clearBatch(); System.out.println(name+"-current count: "+count); connection.disconnectMySQL(); connection=new connection().conn(); statement.close(); statement=connection.conn.prepareStatement(insert); } } statement.executeBatch(); statement.clearBatch(); statement.close(); connection.disconnectMySQL(); paperIDSet.close(); } catch (SQLException e) { e.printStackTrace(); } }
e957fdf7-d5a4-4f21-94fa-f36a78d4d54a
5
public int storeTicket(Ticket tick) { int result = 0; ResultSet rs = null; PreparedStatement statement = null; try { statement = conn.prepareStatement("insert into Tickets (WorkerID_FK, Subject, Pending, Active, Closed) values (?,?,?,?,?)", Statement.RETURN_GENERATED_KEYS); statement.setInt(1, tick.getWorkerID()); statement.setString(2, tick.getSubject()); statement.setBoolean(3, tick.getPending()); statement.setBoolean(4, tick.getActive()); statement.setBoolean(5, tick.getClosed()); statement.executeUpdate(); rs = statement.getGeneratedKeys(); rs.next(); result = rs.getInt(1); } catch(SQLException e){ e.printStackTrace(); } finally { try { if (rs != null) rs.close(); } catch (Exception e) {} try { if (statement != null) statement.close(); } catch (Exception e) {} } return result; }
f54d9ef8-793a-42af-b9c0-1881b20c2753
6
public void initializeMigration(Random random) { Specification spec = getGame().getSpecification(); ServerPlayer player = (ServerPlayer) getOwner(); List<RandomChoice<UnitType>> recruits = player.generateRecruitablesList(); if (spec.hasOption("model.option.immigrants")) { List<AbstractUnit> immigrants = ((UnitListOption) spec.getOption("model.option.immigrants")).getOptionValues(); for (int index = 0; index < Europe.RECRUIT_COUNT; index++) { UnitType immigrant = (index < immigrants.size()) ? immigrants.get(index).getUnitType(getSpecification()) : RandomChoice.getWeightedRandom(null, null, random, recruits); setRecruitable(index, immigrant); } } else { // @compat 0.10.3 for (int index = 0; index < Europe.RECRUIT_COUNT; index++) { String optionId = "model.option.recruitable.slot" + index; if (spec.hasOption(optionId)) { String unitTypeId = spec.getStringOption(optionId).getValue(); if (unitTypeId != null) { setRecruitable(index, spec.getUnitType(unitTypeId)); continue; } } setRecruitable(index, RandomChoice.getWeightedRandom(null, null, random, recruits)); } // end compatibility code } }
3f6c3773-6473-444f-8bf8-7ed6aff82f85
4
@Override public String toString() { String stracc = "Graph: \n"; // Edge: edgeId - VerticeName1(vId1) <=>//=> VerticeName2(vId2) for (Edge e : edges.values()) { Vertice source = vertices.get(e.getSrcVId()); Vertice target = vertices.get(e.getDestVId()); Set<String> attrs = e.getAttrE(); String accuAttuibute = "["; boolean first_attr = true; for (String attr : attrs) { accuAttuibute += ((first_attr) ? "" : "; ") + attr + " => " + e.getStrE(attr); first_attr = false; } String edge = "Edge: " + e.ID + " - "; String sourceS = source.getName() + "(" + source.ID + ")"; String destS = target.getName() + "(" + target.ID + ")"; String direction = (this.isDirected() ? " => " : " <=> "); stracc += edge + sourceS + direction + destS + ": " + accuAttuibute + "]" + "\n"; } return stracc; }
802af6a1-0934-4754-a58c-7ed5d361a91d
9
@SuppressWarnings("unchecked") private byte[] writeEntry(QualifiedValue<?> value) { ByteArrayOutputStream bout = new ByteArrayOutputStream(); CodedOutputStream output = CodedOutputStream.newInstance(bout); try { output.writeInt32(FIELD_ENTRY_ORDER, value.getOrderIndex()); Converter converter = converterFactory.getConverter(value.getValue().getClass()); if (converter != null) { ByteString b = ByteString.copyFrom((byte[]) converter.encode(value.getValue())); output.writeBytes(FIELD_ENTRY_VALUE, b); } else { BaseTypeEncoder encoder = converterFactory.getBaseTypeEncoder(value.getValue().getClass()); if (encoder != null) { encoder.encode(FIELD_ENTRY_VALUE, value.getValue(), output); } else { // No encoder or converter, the value is not persisted } } Set<Enum<?>> qualifiers = value.getQualifiers(); for (Enum<?> qualifier : qualifiers) { String qualifierEncoded = qualifier.getClass().getName() + "@" + qualifier.name(); String id = converterFactory.getEncodedQualifier(qualifierEncoded); if (id != null) { qualifierEncoded = id; } output.writeString(FIELD_ENTRY_QUALIFIER, qualifierEncoded); } output.flush(); } catch (Exception e) { throw new RuntimeException("Could not write qualified value to byte array!", e); } finally { try { bout.close(); } catch (IOException e) { throw new RuntimeException("Could not close output stream!", e); } } return bout.toByteArray(); }
32a4749d-97ef-4026-b097-3df506caf0a2
1
@Test public void logTest(){ Logger log = Logger.getLogger(this.getClass().getName()); assertNotNull(log); log.setLevel(Level.FINEST); LogHandler.initLogFileHandler(log, "test"); File file = new File("logs/test+.log.0"); assertTrue(file.exists()); log.warning("test2"); log.info("Test"); log.finest("test2"); try{ throw new NullPointerException(); } catch(Exception e){ LogHandler.writeStackTrace(log, e, Level.SEVERE); } Long fileLength = file.length(); assertTrue(fileLength > 0L); log.warning("test2"); }
4998b1a4-8289-4c88-a1b2-0db6193bcd91
0
public void initSerie() { TableModel dataModel = new AbstractTableModel() { @Override public String getColumnName(int col) { return titre; } public int getColumnCount() { return 1; } public int getRowCount() { return 8; } public Object getValueAt(int row, int col) { return new Integer(row * col); } }; JTable tableSerie = new JTable(dataModel); tableSerie.getColumnModel().getColumn(0).setPreferredWidth(125); this.add(tableSerie); /* * ImageIcon icon = new ImageIcon("img//gdeFond2.jpg"); JLabel img = new * JLabel(icon); add(img); */ }
35aafed1-59e1-43ba-b658-36ccb8ec7315
8
private static ArrayList<Integer> getIndependenetVirtualDiskKeys(VirtualMachine vm) throws Exception { ArrayList<Integer> diskKeys = new ArrayList<Integer>(); VirtualDevice[] devices = (VirtualDevice[]) vm.getPropertyByPath("config.hardware.device"); for (int i = 0; i < devices.length; i++) { if (devices[i] instanceof VirtualDisk) { VirtualDisk vDisk = (VirtualDisk) devices[i]; String diskMode = ""; VirtualDeviceBackingInfo vdbi = vDisk.getBacking(); if (vdbi instanceof VirtualDiskFlatVer1BackingInfo) { diskMode = ((VirtualDiskFlatVer1BackingInfo) vdbi).getDiskMode(); } else if (vdbi instanceof VirtualDiskFlatVer2BackingInfo) { diskMode = ((VirtualDiskFlatVer2BackingInfo) vdbi).getDiskMode(); } else if (vdbi instanceof VirtualDiskRawDiskMappingVer1BackingInfo) { diskMode = ((VirtualDiskRawDiskMappingVer1BackingInfo) vdbi).getDiskMode(); } else if (vdbi instanceof VirtualDiskSparseVer1BackingInfo) { diskMode = ((VirtualDiskSparseVer1BackingInfo) vdbi).getDiskMode(); } else if (vdbi instanceof VirtualDiskSparseVer2BackingInfo) { diskMode = ((VirtualDiskSparseVer2BackingInfo) vdbi).getDiskMode(); } if (diskMode.indexOf("independent") != -1) { diskKeys.add(vDisk.getKey()); } } } return diskKeys; }
e9e09603-438a-4dfd-bdee-0c4264618fa6
7
private void assignCornerElevations() { LinkedList<Corner> queue = new LinkedList(); for (Corner c : corners) { c.water = isWater(c.loc); if (c.border) { c.elevation = 0; queue.add(c); } else { c.elevation = Double.MAX_VALUE; } } while (!queue.isEmpty()) { Corner c = queue.pop(); for (Corner a : c.adjacent) { double newElevation = 0.01 + c.elevation; if (!c.water && !a.water) { newElevation += 1; } if (newElevation < a.elevation) { a.elevation = newElevation; queue.add(a); } } } }
7af090f1-2c3f-4a57-bbdf-91c43386f119
8
private int getLargestProduct(int numOfAdjacent) { int max = 0; for (int i = numOfAdjacent - 1; i < GRID.length - numOfAdjacent + 1; i++) { for (int j = numOfAdjacent - 1; j < GRID[i].length - numOfAdjacent + 1; j++) { int productUp = 1; int cursor = numOfAdjacent - 1; while (cursor >= 0) { productUp *= GRID[i - cursor--][j]; } max = Math.max(max, productUp); int productDown = 1; cursor = numOfAdjacent - 1; while (cursor >= 0) { productDown *= GRID[i + cursor--][j]; } max = Math.max(max, productDown); int productLeft = 1; cursor = numOfAdjacent - 1; while (cursor >= 0) { productLeft *= GRID[i][j - cursor--]; } max = Math.max(max, productLeft); int productRight = 1; cursor = numOfAdjacent - 1; while (cursor >= 0) { productRight *= GRID[i][j + cursor--]; } max = Math.max(max, productRight); int productSlash = 1; cursor = numOfAdjacent - 1; while (cursor >= 0) { productSlash *= GRID[i - cursor][j + cursor]; cursor--; } max = Math.max(max, productSlash); int productBackslash = 1; cursor = numOfAdjacent - 1; while (cursor >= 0) { productBackslash *= GRID[i + cursor][j - cursor]; cursor--; } max = Math.max(max, productBackslash); } } return max; }
c0238194-0529-4b5d-acf5-80976cbdde95
8
public void setPointDimensions(int count, int numBytes) { if (count <= 0) { throw new IllegalArgumentException("point dimension count must be >= 0; got " + count + " for field=\"" + name + "\""); } if (count > PointValues.MAX_DIMENSIONS) { throw new IllegalArgumentException("point dimension count must be < PointValues.MAX_DIMENSIONS (= " + PointValues.MAX_DIMENSIONS + "); got " + count + " for field=\"" + name + "\""); } if (numBytes <= 0) { throw new IllegalArgumentException("point numBytes must be >= 0; got " + numBytes + " for field=\"" + name + "\""); } if (numBytes > PointValues.MAX_NUM_BYTES) { throw new IllegalArgumentException("point numBytes must be <= PointValues.MAX_NUM_BYTES (= " + PointValues.MAX_NUM_BYTES + "); got " + numBytes + " for field=\"" + name + "\""); } if (pointDimensionCount != 0 && pointDimensionCount != count) { throw new IllegalArgumentException("cannot change point dimension count from " + pointDimensionCount + " to " + count + " for field=\"" + name + "\""); } if (pointNumBytes != 0 && pointNumBytes != numBytes) { throw new IllegalArgumentException("cannot change point numBytes from " + pointNumBytes + " to " + numBytes + " for field=\"" + name + "\""); } pointDimensionCount = count; pointNumBytes = numBytes; }
70dbd862-8c69-4ebb-b2c3-278019a3dba0
0
public IntegerResource(int value) { this.value = value; }
bfbac35a-e42f-4fb6-b324-914d462ccfe8
6
public String getStr(char c1,char c2){ String tmp_str =""; if(c2 == ' '){ tmp_str = "1"+c2; }else{ if(c1==c2 && c1=='1'){ tmp_str = "21"; }else if(c1==c2 && c1=='2'){ tmp_str = "22"; }else if(c1!=c2 ){ tmp_str = "1"+c1+"1"+c2; } } return tmp_str; }
6618c3d2-193c-476c-8a11-b666ba94fd25
8
@Override public Ant run() { Ant bestSoFar = null; final int limit = maxIter / 2; int stagnationCounter = 0; int div = maxIter / 50; final int stagnationLimit = div < 10 ? 10 : div; for (int i = 0; i < maxIter; i++) { List<Ant> ants = new ArrayList<>(l); for (int j = 0; j < l; j++) { Ant ant = new Ant(n, alpha); for (int k = 0; k < n; k++) { ant.findNextNode(distance, candidates, tau, eta); } ants.add(ant); } Ant iterBest = Collections.min(ants); stagnationCounter++; if (stagnationCounter >= stagnationLimit) { stagnationCounter = 0; tauMax = 1 / (ro * bestSoFar.getTotalDistance()); tauMin = tauMax / a; resetTau(); } if (bestSoFar == null || iterBest.compareTo(bestSoFar) < 0) { bestSoFar = iterBest; stagnationCounter = 0; } System.out.println((i + 1) + ": " + bestSoFar.getTotalDistance()); evaporate(); if (i < limit) { refreshTau(iterBest); } else { refreshTau(bestSoFar); } } return bestSoFar; }
dcc4cf94-d706-40a3-ad8c-db9034255305
4
public static String getSignature(String secret, String... values) { if (isBlank(secret)) { throw new IllegalArgumentException("The value of 'secret' can't be blank."); } if (values == null || values.length < 1) { throw new IllegalArgumentException("The 'values' can't be null or empty."); } final StringBuilder sb = new StringBuilder(); for (String value : values) { sb.append(md5(value)); } sb.append(md5(secret)); return md5(sb.toString()); }
94b9c323-20eb-4192-959d-a1cff8499300
2
protected static String containedText(Node node) { NodeList children = node.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { Node c = children.item(i); if (c.getNodeType() != Node.TEXT_NODE) continue; return ((Text) c).getData(); } return null; }
066d3494-0e3d-4c5b-bf4d-40ab5fd4179d
3
public void waitTillDone() { while (true) { Thread t = threadVar.get(); if (t == null) { return; } try { t.join(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); // propagate return; } } }
91a0b700-0c3f-498f-937a-c9691ca1742d
2
void hideMe() { for (int i=100; i>0; i--) { label.setForeground(new Color(1, 1, 1, (float)i / 100f)); label.setBackground(new Color(0, 0, 0, (float)i / 100f)); label.setBorder(BorderFactory.createLineBorder(new Color(0, 0, 0, (float)i / 100f), 5, false)); try { Thread.sleep(5); } catch (InterruptedException e) { label.setForeground(Color.WHITE); label.setBackground(Color.BLACK); label.setBorder(BorderFactory.createLineBorder(Color.BLACK, 5, true)); return; } } setVisible(false); label.setForeground(Color.WHITE); label.setBackground(Color.BLACK); label.setBorder(BorderFactory.createLineBorder(Color.BLACK, 5, true)); }
59f5be66-c00d-4f72-90bd-78edbf702277
0
@XmlElementWrapper(name = "data") @XmlElement(name = "EmailKontakt") public ArrayList<EmailKontakt> getContactList() { return contactList; }
2addc93d-07a3-4b03-a4a4-0bd5d3bf668e
7
protected BeanAutoDetect(Class<?> clazz) throws DaoGenerateException { this.clazz = clazz; Map<String, PropertyDescriptor> descriptors; try { descriptors = IntrospectorUtils.getPropertyDescriptors(clazz); } catch (Exception e) { throw new DaoGenerateException("解析类[" + clazz + "]失败:", e); } for (Entry<String, PropertyDescriptor> entry : descriptors.entrySet()) { String property = entry.getKey(); PropertyDescriptor descriptor = entry.getValue(); Method writeMethod = descriptor.getWriteMethod(); Class<?> type = descriptor.getPropertyType(); if (writeMethod != null) { if (type == null || !isAllowAutoMapType(type)) { throw new DaoGenerateException("[" + clazz + "]中包含不可识别的属性类型[" + type + "]"); } writeMethod.setAccessible(true); writeMethods.put(property, writeMethod); propertyTypes.put(property, type); } } }
82ca4fd4-2256-4eae-bdf3-8a94a7471bf9
8
public static String checkStatus(String dirName) { GetAbsolutePath pt = new GetAbsolutePath(); String absolutePath = pt.getPath(); File directory = new File(absolutePath + dirName); File outFile = new File(absolutePath + dirName + "/outfile"); File outTree = new File(absolutePath + dirName + "/outtree"); String status =""; boolean exists1 = directory.exists(); boolean exists2 = outFile.exists(); boolean exists3 = outTree.exists(); if (exists1 == false) status = "Job Not Found"; else { if (dirName.contains("PhylipConsense") || dirName.contains("PhylipNeighbor") || dirName.contains("PhylipProtpars")) { if (exists2 == true && exists3 == true) status = "FINISHED"; else status = "RUNNING"; }//if else if (dirName.contains("PhylipProtdist")) { if (exists2 == true ) status = "FINISHED"; else status = "RUNNING"; }//else }//else return status; }//checkStatus
5d727db4-638b-46c5-b634-595cbe77d24e
0
public void setContentType(String contentType) { this.contentType = contentType; }
d103ab73-1c3f-4c96-ab81-ec0172839172
1
public Coord3d[] returnCommonCoordinates() { Coord3d[] temp = new Coord3d[commonCoordinates.size()]; for (int i = 0; i < commonCoordinates.size(); i++) { temp[i] = commonCoordinates.get(i); } return temp; }
6821ceda-fad8-4153-bd6c-c55a05fe2bf0
2
public static void main(String[] args) { List<Product> list = new ArrayList<Product>(); Product pro = null; for(int i=0;i<2;i++){ pro = new Product(); pro.setSku("1"+i); pro.setName("峻德"+i); pro.setDescription("1"+i); pro.setOnline("1"+i); list.add(pro); } ComparatorProduct compare = new ComparatorProduct(); Collections.sort(list,compare); for (int i = 0; i < list.size(); i++) { Product p = (Product)list.get(i); System.out.println(p.getName() + "," + p.getSku()); } }
6378d3b1-0d26-4a2d-8665-20cc2183792e
7
public static boolean unequipItem(Hero owner, Item item) { if (owner != null && item != null && isItemEquipped(owner, item)) { // item is equipped -> remove it // set owner to null for item abilities // so that a unit cannot use them anymore owner.getEquipment().remove(item); Set<Ability> abilities = item.getAbilities(); if (abilities != null) { for (Ability ability : abilities) { // create event for gameEventController Map<GameEventParameter, Object> eventParams = new HashMap<GameEventParameter, Object>(); eventParams.put(GameEventParameter.TRIGGERING_UNIT, owner); eventParams.put(GameEventParameter.TRIGGERING_ABILITY, ability); GameEventHandler.INSTANCE.createAndDispatchEvent(GameEventType.UNIT_REMOVE_ABILITY, owner, eventParams); ability.setOwner(null); if (LOGGER.isDebugEnabled()) LOGGER.debug("Successfully removed itemability '" + ability + "' from hero '" + owner + "'"); } } // add item to inventory owner.getInventory().add(item); if (LOGGER.isDebugEnabled()) LOGGER.debug("Successfully removed equipment item '" + item + "' from hero " + owner); return true; } return false; }
b2166e1e-eb1b-4536-8917-cbf4a263111a
6
static public BufferedImage[] loadImages(File f) throws IOException { InputStream istream = new FileInputStream(f); BufferedInputStream buffin = new BufferedInputStream(istream); BinaryInputStream in = new BinaryInputStream(buffin); try { in.mark(32000); IconDir dir = new IconDir(in); // System.out.println("DIR = " + dir); IconEntry[] entries = new IconEntry[dir.idCount]; BufferedImage[] images = new BufferedImage[dir.idCount]; for (int i = 0; i < dir.idCount; i++) { entries[i] = new IconEntry(in); // System.out.println("ENTRY " + i + " = " + entries[i]); } IconEntry entry = entries[0]; // System.out.println("ENTRYx = " + entry); for (int i = 0; i < dir.idCount; i++) { in.reset(); in.skip(entries[i].imageOffset); IconHeader header = new IconHeader(in); // System.out.println("Header: " + header); long toskip = header.size - 40; if (toskip > 0) { in.skip((int) toskip); } // System.out.println("skipped data"); BufferedImage image = new BufferedImage((int) header.width, (int) header.height / 2, BufferedImage.TYPE_INT_ARGB); switch (header.bitsPerPixel) { case 4: case 8: loadPalettedImage(in, entries[i], header, image); break; default: throw new Exception("Unsupported ICO color depth: " + header.bitsPerPixel); } images[i] = image; } return images; } catch (Exception exc) { } return null; }
24565a6f-47ed-40ac-ad60-220be9dd532d
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(AddTimeLog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(AddTimeLog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(AddTimeLog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(AddTimeLog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* * Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { new AddTimeLog().setVisible(true); } }); }
5e87656f-50e9-49a9-9d03-fe6863fc1c96
3
public static int[] analyzeHistogram(ImageData imageData) { int height = imageData.height; int width = imageData.width; int depth = imageData.depth; int[] histogram = new int[256]; int c = 0; for (int i = 0; i < height; i++) {// height for (int j = 0; j < width; j++) {// width // byte gray = imageData.data[c++]; // gray &= 0xFF;// Calculate Gray // System.out.print(gray + "-"); int pixel = imageData.getPixel(j, i); switch (imageData.depth) { case 24: int R = pixel >> 16; int G = (pixel - (R << 16)) >> 8; int B = (pixel - (R << 16) - (G << 8)); pixel = (int) (0.299 * R + 0.587 * G + 0.114 * B); } histogram[pixel]++; } // System.out.println(); } return histogram; }
737f8850-44d7-4f42-8c63-450fb111fa83
1
@Override public String[] getPresentStatusLog() { ArrayList<String> statusLog = new ArrayList<String>(); for (int i = 0; i < defaultStatusList.size(); i++) { statusLog.add(defaultStatusList.getElementAt(i)); } return statusLog.toArray(new String[statusLog.size()]); }
e1bbdf20-4e80-4bad-9739-c3a99327cb32
4
public void run(String[] args) throws Exception { if (args.length == 1) { int selectedIndex = 1; String proto = null; try { PCSCManager.connect(selectedIndex, proto); } catch (Exception e) { selectedIndex = -1; } if (selectedIndex == -1 || proto == null) Logger.log("Uso: " + getTemplate()); } else { String[] params = StringUtil.tokenize(args[1]); PCSCManager.connect(Integer.parseInt(params[0]), params[1]); } }
5cab3384-2b3a-4130-b8fa-750c9ce6277b
0
public void setFechaRecogida(String fechaRecogida) { this.fechaRecogida = fechaRecogida; }
9849e9d8-cc6d-4c0e-b62c-72a7c158b274
7
private MidiDevice openMidiDevice( String containsString ) { message( "Searching for MIDI device with name containing '" + containsString + "'" ); MidiDevice device = null; MidiDevice.Info[] midiDevices = MidiSystem.getMidiDeviceInfo(); for( int i = 0; i < midiDevices.length; i++ ) { device = null; try { device = MidiSystem.getMidiDevice( midiDevices[i] ); } catch( MidiUnavailableException e ) { message( " Problem in method 'getMidiDevice': " + "MIDIUnavailableException was thrown" ); device = null; } if( device != null && midiDevices[i].getName().contains( containsString ) ) { message( " Found MIDI device named '" + midiDevices[i].getName() + "'" ); if( device instanceof Synthesizer ) message( " *this is a Synthesizer instance" ); if( device instanceof Sequencer ) message( " *this is a Sequencer instance" ); try { device.open(); } catch( MidiUnavailableException mue ) { message( " Unable to open this MIDI device" ); device = null; } return device; } } message( " MIDI device not found" ); return null; }
5540801f-fb3b-4342-a494-0399b61af78e
4
public boolean mousedown(Coord c, int button) { if(a || button != 1 || c.y < 16 || c.y > sz.y - 10) return(false); check(this); return(true); }
21ef9a6c-a646-44ec-bb87-a3eb67139342
8
public static Function getFunction(Library l, Object o) { Dictionary d = null; if (o instanceof Reference) { o = l.getObject((Reference) o); } // create a dictionary out of the object if possible if (o instanceof Dictionary) { d = (Dictionary) o; } else if (o instanceof Hashtable) { d = new Dictionary(l, (Hashtable) o); } if (d != null) { // find out what time of function type and create the appropriate // function object. int fType = d.getInt("FunctionType"); switch (fType) { // sampled function case 0: return new Function_0(d); // exponential interpolation case 2: return new Function_2(d); // stitching function case 3: return new Function_3(d); // PostScript calculator case 4: return new Function_4(d); } } return null; }
37e3d7ab-9ee6-42c3-acd5-aa2d8affd0f1
4
private Method findFromStringMethod(Class<?> cls, String methodName) { Method m; try { m = cls.getMethod(methodName, String.class); } catch (NoSuchMethodException ex) { try { m = cls.getMethod(methodName, CharSequence.class); } catch (NoSuchMethodException ex2) { throw new IllegalArgumentException("Method not found", ex2); } } if (Modifier.isStatic(m.getModifiers()) == false) { throw new IllegalArgumentException("Method must be static: " + methodName); } return m; }
549271b0-74da-4cae-a716-21d165aadaab
6
private void checkAlive() { ArrayList<ComponentEntry> removeList = new ArrayList<ComponentEntry>(); long now = System.currentTimeMillis(); for (ComponentEntry ap : this.accessPoints.values()) { if (ap.timestamp+timeout < now) { removeList.add(ap); } } for (ComponentEntry ap : removeList) { disassociateAP(ap); } removeList = new ArrayList<ComponentEntry>(); for (ComponentEntry ac : this.accessControllers.values()) { if (ac.timestamp+timeout < now) { removeList.add(ac); } } for (ComponentEntry ac : removeList) { disassociateAC(ac); } }
6b897b4c-bf39-4c0b-b147-0469113c63d4
5
public WordSearch(String filename, String name) { this.name = name; try { scanner = new Scanner(new File(filename)); } catch (FileNotFoundException e) { e.printStackTrace(); } this.n = scanner.nextInt(); this.m = scanner.nextInt(); puzzle = new String[n]; for (int i = 0; i < n; i++) { puzzle[i] = scanner.next(); } puzzle2DArray = new char[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { puzzle2DArray[i][j] = puzzle[i].charAt(j); } } while (scanner.hasNext()) { clues = clues + scanner.next() + " "; } numberOfTrials = clues.split(" ").length; }
242441b4-050d-48ae-a810-e701042d8894
0
public boolean getTeam() { return this.team; }
b43199a9-bfd5-4ac0-8acc-477bdf1d04e6
6
public MethodAnalyzer(ClassAnalyzer cla, MethodInfo minfo, ImportHandler imports) { this.classAnalyzer = cla; this.imports = imports; this.minfo = minfo; this.methodName = minfo.getName(); this.methodType = Type.tMethod(minfo.getType()); this.isConstructor = methodName.equals("<init>") || methodName.equals("<clinit>"); if (minfo.getBytecode() != null) { code = minfo.getBytecode(); } String[] excattr = minfo.getExceptions(); if (excattr == null) { exceptions = new Type[0]; } else { int excCount = excattr.length; this.exceptions = new Type[excCount]; for (int i = 0; i < excCount; i++) exceptions[i] = Type.tClass(excattr[i]); } if (minfo.isSynthetic() || methodName.indexOf('$') != -1) synth = new SyntheticAnalyzer(minfo, true); }
5bcc24f5-d035-420e-a09d-6164bbd49931
5
public static void injectValueInStaticField(Class<?> clazz, String fieldName, Object value) throws JStrykerException, IllegalArgumentException { if (clazz == null) { throw new IllegalArgumentException("Clazz cannot be null."); } if (fieldName == null) { throw new IllegalArgumentException("Field name cannot be null."); } try { Field field = clazz.getDeclaredField(fieldName); field.setAccessible(true); field.set(clazz, value); } catch (NoSuchFieldException e) { String message = String.format("%s does not have field %s.", clazz, fieldName); throw new JStrykerException(message, e); } catch (IllegalAccessException e) { throw new JStrykerException(e.getMessage(), e); } }
bf9fca0f-3895-4a09-b32f-95c98d071f08
1
public void showHideNavigator() { if (!toolbar.getTreeSelected()) center.remove(navigator); else center.add(BorderLayout.WEST, navigator); center.revalidate(); center.repaint(); }
97a175af-1f04-4e80-ada7-8525f49d1cf8
7
public static ArrayList<Object> getObjects(List<?> rows, Class<?> decoratorClass) { ArrayList<Object> resultList = new ArrayList<Object>(); Object firstRow = rows.get(0); Class<? extends Object> rowClass = firstRow.getClass(); Integer lp = 1; for (Object row : rows) { try { Constructor<?> constructor = decoratorClass .getDeclaredConstructor(rowClass); DecoratorTable decorator = (DecoratorTable) constructor .newInstance(row); decorator.setLp("<span class='lp'>" + lp + "</span>"); String checkbox = (decorator.getCheckbox() != null ? decorator .getCheckbox() : ""); decorator.setCheckbox(checkbox + "<input class='checkbox' type='checkbox'/>"); resultList.add(decorator); lp++; } catch (Exception e) { e.printStackTrace(); } } return resultList; }
a72759ad-dd44-4926-bc6e-4235a0a09579
6
public boolean isBlackJack() { boolean hasAce = false; boolean hasTen = false; for ( int i = 0; i < hand.size(); i++ ) { if ( hand.get(i).getFace() == Rank.ACE ) { hasAce = true; break; } } for ( int i = 0; i < hand.size(); i++ ) { if ( hand.get(i).getValues().get(0) == 10 ) { hasTen = true; break; } } return hasTen && hasAce && hand.size() == 2; }
0192cf22-8ece-44e0-80ca-49d002c02255
9
private final void draw0(byte[] is, int[] is_25_, int i, int i_26_, int i_27_, int i_28_, int i_29_, int i_30_, int i_31_, int i_32_, int i_33_, int i_34_, aa var_aa, int i_35_, int i_36_) { aa_Sub3 var_aa_Sub3 = (aa_Sub3) var_aa; int[] is_37_ = ((aa_Sub3) var_aa_Sub3).anIntArray5201; int[] is_38_ = ((aa_Sub3) var_aa_Sub3).anIntArray5202; int i_39_ = i_33_; if (i_36_ > i_39_) { i_39_ = i_36_; i_27_ += (i_36_ - i_33_) * ((SoftwareToolkit) softwareToolkit).maxWidth; i_26_ += (i_36_ - i_33_) * i_34_; } int i_40_ = (i_36_ + is_37_.length < i_33_ + i_29_ ? i_36_ + is_37_.length : i_33_ + i_29_); for (int i_41_ = i_39_; i_41_ < i_40_; i_41_++) { int i_42_ = i_35_ + is_37_[i_41_ - i_36_]; int i_43_ = is_38_[i_41_ - i_36_]; int i_44_ = i_28_; if (i_32_ > i_42_) { int i_45_ = i_32_ - i_42_; if (i_45_ >= i_43_) { i_26_ += i_28_ + i_31_; i_27_ += i_28_ + i_30_; continue; } i_43_ -= i_45_; } else { int i_46_ = i_42_ - i_32_; if (i_46_ >= i_28_) { i_26_ += i_28_ + i_31_; i_27_ += i_28_ + i_30_; continue; } i_26_ += i_46_; i_44_ -= i_46_; i_27_ += i_46_; } int i_47_ = 0; if (i_44_ < i_43_) i_43_ = i_44_; else i_47_ = i_44_ - i_43_; for (int i_48_ = 0; i_48_ < i_43_; i_48_++) { if (is[i_26_++] != 0) is_25_[i_27_++] = i; else i_27_++; } i_26_ += i_47_ + i_31_; i_27_ += i_47_ + i_30_; } }
b40a4bf1-2e8d-4534-a7d2-82f4f8531b7c
0
public void mousePressed(MouseEvent e) { // TODO Auto-generated method stub }
b6358854-89b7-4485-8f95-b9fc88686418
8
private TextAnchor textAlignPtForLabelAnchorV(RectangleAnchor anchor) { TextAnchor result = TextAnchor.CENTER; if (anchor.equals(RectangleAnchor.TOP_LEFT)) { result = TextAnchor.TOP_RIGHT; } else if (anchor.equals(RectangleAnchor.TOP)) { result = TextAnchor.TOP_CENTER; } else if (anchor.equals(RectangleAnchor.TOP_RIGHT)) { result = TextAnchor.TOP_LEFT; } else if (anchor.equals(RectangleAnchor.LEFT)) { result = TextAnchor.HALF_ASCENT_RIGHT; } else if (anchor.equals(RectangleAnchor.RIGHT)) { result = TextAnchor.HALF_ASCENT_LEFT; } else if (anchor.equals(RectangleAnchor.BOTTOM_LEFT)) { result = TextAnchor.BOTTOM_RIGHT; } else if (anchor.equals(RectangleAnchor.BOTTOM)) { result = TextAnchor.BOTTOM_CENTER; } else if (anchor.equals(RectangleAnchor.BOTTOM_RIGHT)) { result = TextAnchor.BOTTOM_LEFT; } return result; }
458c260a-88dd-4696-ac78-4f86095828bf
4
@Override public void run() { for (Player player : World.getWorld().getPlayers()) { try { if (player.getSession().getSocketChannel().isOpen()) { for (Packet packet = player.getPacketQueue().poll(); packet != null; packet = player.getPacketQueue().poll()) { PacketManager.handlePacket(player, packet); player.setPacketReceived(packet.getOpcode(), false); } } } catch (Exception e) { e.printStackTrace(); } } }
15fea06c-2363-4f7c-8ae5-e292a0e2de17
0
@Override public void setGUITreeComponentID(String id) {this.id = id;}
cf0ae0d8-811e-4902-8916-c35fe4066f6b
6
public static void ledprocess(String filepath, String result, String sn){ String finalresult = ""; int errorcode=0;// print error code in the final output file; int errornum = 7; File outputfile = new File(filepath); if ((result.equals("P"))||(result.equals("p"))||(result.equals("pass"))||(result.equals("PASS"))){ finalresult = "PASS"; } else { finalresult="FAILED"; errorcode = 0; } try { BufferedWriter bw = new BufferedWriter(new FileWriter(outputfile, true));// append the content to the end instead of overwriting the prior contents. bw.write("LED_White_Result="+finalresult+"\r\n"); System.out.println("LED_White_Result="+finalresult); if (finalresult.equals("FAILED")){ NumberFormat nf = NumberFormat.getIntegerInstance(); nf.setMinimumIntegerDigits(2); bw.write("Error_Code="+nf.format(errornum)+nf.format(errorcode)+"\r\n"); System.out.println("Error_Code="+nf.format(errornum)+nf.format(errorcode)); } bw.flush(); bw.close(); } catch (IOException e) { e.printStackTrace(); } }
cee505d5-9e74-4d1b-9f53-8450f452d115
9
@Override public Object getValueAt(int row, int col) { String colName = getColumnName(col); switch (colName) { case "Select": return selectList.get(row); case "Status": return entries.get(row).getStatus().toString(); case "Text": return entries.get(row).getText(); case "Add Date": Date addDate = entries.get(row).getAddDate(); if (addDate != null) { return addDate.toString(); } else { return ""; } case "Edit Date": Date editDate = entries.get(row).getEditDate(); if (editDate != null) { return editDate.toString(); } else { return ""; } case "Tree": return entries.get(row).getTreeString(); case "Dependency": return entries.get(row).getDependency().toString(); default: return "ERROR"; } }
2ea31359-0e3f-41e0-adfb-cc490524d17d
5
public void drawObjects(BufferedImage canvas, boolean fill) { BufferedImage image = new BufferedImage(_width, _height, BufferedImage.TYPE_INT_RGB); Graphics2D g = image.createGraphics(); g.drawImage(VisionUtils.convert2grey(canvas), 0, 0, null); // draw ground level for (int x = 0; x < _width; x++) { image.setRGB(x, _ground, 0xff0000); } if (fill) { //draw connected components for (ConnectedComponent d : _draw) d.draw(image, false, false); } //System.out.println(" draw shape " + _gameObjects.size()); for (Body b : _drawShape) { //System.out.println(" draw shape"); if (b != null) b.draw(g, false, Color.RED); } canvas.createGraphics().drawImage(image, 0, 0, null); }
de1375f2-79d7-4548-be7f-9bb52e4ad833
5
public void actionPerformed(ActionEvent e) { while (true) { String name = JOptionPane.showInputDialog("Enter name"); String number = JOptionPane.showInputDialog("Enter number"); if (name == null || number == null) { gui.messageArea.setText("Canceled"); break; } else if (name.equals("") || number.equals("")) { JOptionPane.showMessageDialog(gui, "Input name and number"); } else { phoneBook.put(name, number); gui.messageArea.setText(name + " added"); break; } } }
9aeca423-a767-43b4-adfb-cccf1ec38ef9
3
public static void main(String[] args) { // TODO Auto-generated method stub int[][] res = generateMatrix(0); for (int i = 0; i < res.length; i++) { for (int j = 0; j < res[i].length; j++) { System.out.print(res[i][j] + " "); } System.out.println(); } int[][] matrix = {{1},{2},{3},{4},{5},{6}}; List<Integer> r = spiralOrder(matrix); for (Integer i : r) { System.out.print(i + " "); } }
3b14aa66-e9af-45ad-8797-c6ee438e473f
8
public String toString(){ StringBuffer sb = new StringBuffer(); switch(type){ case TYPE_VALUE: sb.append("VALUE(").append(value).append(")"); break; case TYPE_LEFT_BRACE: sb.append("LEFT BRACE({)"); break; case TYPE_RIGHT_BRACE: sb.append("RIGHT BRACE(})"); break; case TYPE_LEFT_SQUARE: sb.append("LEFT SQUARE([)"); break; case TYPE_RIGHT_SQUARE: sb.append("RIGHT SQUARE(])"); break; case TYPE_COMMA: sb.append("COMMA(,)"); break; case TYPE_COLON: sb.append("COLON(:)"); break; case TYPE_EOF: sb.append("END OF FILE"); break; } return sb.toString(); }
8b0f4091-5557-412c-b438-07fc8e06c380
7
static void sendPBNotification(final Context context, String displayScore) { if((flags & FLAG_NO_NOTIFICATION) > 0) return; final String appName = Utils.getAppLabel(context); if (appName == null) { return; } if (Utils.packageIsInstalled(HEYZAP_PACKAGE, context) || !Utils.marketInstalled(context) || !Utils.androidVersionSupported()) { return; } long now = System.nanoTime() / 1000000000; long last = context.getSharedPreferences(LAST_PB_NOTIF, 0).getLong("seconds", 0l); // only once every 24 hours if (last == 0 || (now - last) < 60 * 60 * 24) { // save the time Editor editor = context.getSharedPreferences(LAST_PB_NOTIF, 0).edit(); editor.putLong("seconds", now); editor.commit(); // actually create the notification HeyzapNotification.sendPB(context, appName, displayScore); } }
d904c549-6f6d-472b-8294-88672da5f716
9
@Override protected void processElement(final XMLStreamReader reader, final Mop item) throws XMLStreamException { switch (reader.getNamespaceURI()) { case NAMESPACE: switch (reader.getLocalName()) { case "Geometrie": Utils.processGeometrie( reader, getConnection(), item, NAMESPACE); break; case "GlobalniIdNavrhuZmeny": item.setNzIdGlobalni( Long.parseLong(reader.getElementText())); break; case "IdTransakce": item.setIdTransRuian( Long.parseLong(reader.getElementText())); break; case "Kod": item.setKod( Integer.parseInt(reader.getElementText())); break; case "Nazev": item.setNazev(reader.getElementText()); break; case "Nespravny": item.setNespravny( Boolean.valueOf(reader.getElementText())); break; case "Obec": item.setObecKod(Utils.getObecKod(reader, NAMESPACE)); break; case "PlatiOd": item.setPlatiOd( Utils.parseTimestamp(reader.getElementText())); break; default: XMLUtils.processUnsupported(reader); } break; default: XMLUtils.processUnsupported(reader); } }
da381544-be87-4446-afe7-6f132d8bba11
2
public void mousePressed(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON1) Main.isMouseLeft = true; else if (e.getButton() == MouseEvent.BUTTON3) Main.isMouseRight = true; }
083a5dab-c8f2-4442-a199-29d2520d0e9b
2
@Override public int matches( short[] sequenceA, int indexA, short[] sequenceB, int indexB, int count ) { for (int i = 0; i < count; i++) { if (sequenceA[indexA + i] != sequenceB[indexB + i]) { return i; } } return count; }
75c63855-43e8-418a-8051-e8fad4c8c304
5
private void dfs(Graph<?> g, Object v, boolean alt) { this.marked.put(v, true); //System.out.println(v); //System.out.println(this); for (Object temp : g.getAdjacentVertices(v)) { if (!marked.get(temp)) { this.color.put(temp, alt); dfs(g, temp, !alt); } if (!isBipartite) break; if (this.color.get(temp) != alt) { isBipartite = false; break; } /*System.out.println(v+"->"+temp); System.out.println(this.color); System.out.println("alt=" +alt);*/ } }
e00fc14c-ed61-4b21-b992-f9a6cf5eb590
5
public static void main(String[] args) { // TODO Auto-generated method stub Scanner in = new Scanner(System.in); while (in.hasNextInt()) { int a = in.nextInt(); if ( a == 0 ) break; for ( int k = 1;;k++) { // Try m // Target : J(a,m,a) = 2 // Initial : J(1,m,1) = 0 int s = 0; for ( int i = 2;i < a;i++) { // Calc J(i,m,i) s = (k+s) % i; } if ( s == 0 ) { System.out.println(k); break; } } } }
bce2b295-9859-4ab3-a0ff-93938202e3fc
4
protected void pageChange(int newPageIndex) { switch (newPageIndex) { case indexSRC: if (isDirty()) updateTextEditorFromTable(); break; case indexTBL: if (isDirty()) updateTableFromTextEditor(); break; } isPageModified = false; super.pageChange(newPageIndex); }
ea104fa7-1c69-4be3-a20e-02d1db2e6e86
4
public void gaussianProbabilityPlot(){ this.lastMethod = 0; // Check for suffient data points this.gaussianNumberOfParameters = 2; if(this.numberOfDataPoints<3)throw new IllegalArgumentException("There must be at least three data points - preferably considerably more"); // Create instance of Regression Regression min = new Regression(this.sortedData, this.sortedData); double meanest = this.mean; if(this.mean==0)meanest = this.standardDeviation/3.0; double[] start = {meanest, this.standardDeviation}; this.initialEstimates = start; double[] step = {0.3*meanest, 0.3*this.standardDeviation}; double tolerance = 1e-10; // Add constraint; sigma>0 min.addConstraint(1, -1, 0); // Create an instance of GaussProbPlotFunc GaussProbPlotFunc gppf = new GaussProbPlotFunc(); gppf.setDataArray(this.numberOfDataPoints); // Obtain best probability plot varying mu and sigma // by minimizing the sum of squares of the differences between the ordered data and the ordered statistic medians min.simplex(gppf, start, step, tolerance); // Get mu and sigma for best correlation coefficient this.gaussianParam = min.getBestEstimates(); // Get mu and sigma errors for best correlation coefficient this.gaussianParamErrors = min.getBestEstimatesErrors(); // Calculate Gaussian order statistic medians this.gaussianOrderMedians = Stat.gaussianOrderStatisticMedians(this.gaussianParam[0], this.gaussianParam[1], this.numberOfDataPoints); // Regression of the ordered data on the Gaussian order statistic medians Regression reg = new Regression(this.gaussianOrderMedians, this.sortedData); reg.linear(); // Intercept and gradient of best fit straight line this.gaussianLine = reg.getBestEstimates(); // Estimated erors of the intercept and gradient of best fit straight line this.gaussianLineErrors = reg.getBestEstimatesErrors(); // Correlation coefficient this.gaussianCorrCoeff = reg.getSampleR(); // Initialize data arrays for plotting double[][] data = PlotGraph.data(2,this.numberOfDataPoints); // Assign data to plotting arrays data[0] = this.gaussianOrderMedians; data[1] = this.sortedData; data[2] = this.gaussianOrderMedians; for(int i=0; i<this.numberOfDataPoints; i++){ data[3][i] = this.gaussianLine[0] + this.gaussianLine[1]*this.gaussianOrderMedians[i]; } // Get sum of squares this.gaussianSumOfSquares = min.getSumOfSquares(); if(!this.supressPlot){ // Create instance of PlotGraph PlotGraph pg = new PlotGraph(data); int[] points = {4, 0}; pg.setPoint(points); int[] lines = {0, 3}; pg.setLine(lines); pg.setXaxisLegend("Gaussian Order Statistic Medians"); pg.setYaxisLegend("Ordered Data Values"); pg.setGraphTitle("Gaussian probability plot: gradient = " + Fmath.truncate(this.gaussianLine[1], 4) + ", intercept = " + Fmath.truncate(this.gaussianLine[0], 4) + ", R = " + Fmath.truncate(this.gaussianCorrCoeff, 4)); pg.setGraphTitle2(" mu = " + Fmath.truncate(this.gaussianParam[0], 4) + ", sigma = " + Fmath.truncate(this.gaussianParam[1], 4)); // Plot pg.plot(); } this.gaussianDone = true; }
c2fd6d8c-7530-4377-9ae7-7cdea2a212ec
4
@Override public void valueChanged(ListSelectionEvent e) { JList lsm = (JList) e.getSource(); if (lsm == ticketList) { int selectedIndex = lsm.getSelectedIndex(); if (selectedIndex >= 0) { currentTicket = selectedIndex; priceField.setText(String.valueOf(tickets.get(currentTicket).getTicketCost())); int placeID = tickets.get(currentTicket).getPlace().getPlaceID(); int findIndex = 0; for (int i = 0; i< places.size(); i++) { if (places.get(i).getPlaceID() == placeID) { findIndex = i; break; } } placeSelector.setSelectedIndex(findIndex); frame.revalidate(); } } }
746e551c-077d-4bf9-8613-74bbd2a91c4a
6
public Topology2D(Base basis, int coarseness, Space space){ this.basis = basis; this.coarseness = Math.abs(coarseness); switch(space.getTau()){ case "Cylinder": this.space = Topology2D.Cylinder.class; break; case "Torus": this.space = Topology2D.Torus.class; break; case "Moebius": this.space = Topology2D.Moebius.class; break; case "Klein": this.space = Topology2D.Klein.class; break; default: this.space = Topology2D.Standard.class; break; } Class<?>[] args0 = {int.class, int.class, int.class, int.class}; try { this.idI = this.space.getMethod("idI", args0); this.idJ = this.space.getMethod("idJ", args0); } catch (NoSuchMethodException | SecurityException e) { e.printStackTrace(); } }
237f5acd-ca63-4984-8a22-5c95670fa70d
0
public void setProblemList(ProblemList problemList) { this.problemList = problemList; }
e849426f-d14b-4a8f-8bbb-0529e9af7ad4
3
@Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Email other = (Email) obj; if (!Objects.equals(this.endereco, other.endereco)) { return false; } return true; }
c2215181-162d-481f-97ef-46118d7a9534
0
public UpgradeManager() { this.allUpgrades = new Upgrade[]{ new Upgrade(UpgradeType.Body, "Bodyup 1", null), new Upgrade(UpgradeType.Head, "Headup 1", null), new Upgrade(UpgradeType.Body, "Bodyup 2", null) }; this.allHeads = new Head[]{ new Head(1, "Head 1"), new Head(1, "Head 2") }; this.allBodys = new Body[]{ new Body(1, "Body 1"), new Body(2, "Body 2") }; this.allLimbs = new Limbs[]{ new Limbs(1, "Limbs 1") }; }
1e7032fa-daae-4d37-9e71-6d25c2848831
3
public AST Q() { // Q -> R | R Q AST r = R(); String next = toks.peek(); if(isAlphabetic(next) || "(".equals(next) || isNumber(next)) return new Product(r, Q()); else return r; // I don't think I should *always* do this // (e.g., if I peek and the R is followed // by a number, word, or left parenthesis, // I should try to recurively grab at least // one more R via Q...) }
0589df42-ff54-4f9c-a274-b005527cc5a5
6
public boolean equals(Object other) { if(other == null || !(other instanceof Observation)) return false; Observation o = (Observation) other; if(this.itype != o.itype) return false; if(this.obsID != o.obsID) return false; if(!this.position.equals(o.position)) return false; if(this.category != o.category) return false; return true; }
c36bb677-70d7-4a7d-85ad-1ee86fb1ecf3
3
public SettingsView() { GridBagLayout gridBagLayout = new GridBagLayout(); gridBagLayout.columnWidths = new int[] { 0, 0 }; gridBagLayout.rowHeights = new int[] { 0, 235, 0, 0 }; gridBagLayout.columnWeights = new double[] { 1.0, Double.MIN_VALUE }; gridBagLayout.rowWeights = new double[] { 0.0, 1.0, 0.0, Double.MIN_VALUE }; setLayout(gridBagLayout); final JComboBox<String> comboBox = new JComboBox<String>(); comboBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { switch (comboBox.getSelectedIndex()) { case 0: table.setModel(new ContestantTableModel()); break; case 1: table.setModel(new ProblemTableModel()); break; case 2: table.setModel(new LanguageTableModel()); break; } } }); comboBox.setModel(new DefaultComboBoxModel<String>(new String[] { "Contestants", "Problems", "Languages" })); GridBagConstraints gbc_comboBox = new GridBagConstraints(); gbc_comboBox.insets = new Insets(0, 0, 5, 0); gbc_comboBox.fill = GridBagConstraints.HORIZONTAL; gbc_comboBox.gridx = 0; gbc_comboBox.gridy = 0; gbc_comboBox.gridwidth = 2; add(comboBox, gbc_comboBox); JScrollPane scrollPane = new JScrollPane(); GridBagConstraints gbc_scrollPane = new GridBagConstraints(); gbc_scrollPane.insets = new Insets(0, 0, 5, 0); gbc_scrollPane.fill = GridBagConstraints.BOTH; gbc_scrollPane.gridx = 0; gbc_scrollPane.gridy = 1; gbc_scrollPane.gridwidth = 2; add(scrollPane, gbc_scrollPane); table = new JTable(); /* * GridBagConstraints gbc_table = new GridBagConstraints(); * gbc_table.insets = new Insets(0, 0, 5, 0); gbc_table.fill = * GridBagConstraints.BOTH; gbc_table.gridx = 0; gbc_table.gridy = 1; * gbc_table.gridwidth = 2; add(table, gbc_table); */ table.setModel(new ContestantTableModel()); scrollPane.getViewport().add(table, null); JButton btnAdd = new JButton("Add"); btnAdd.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Add to current table // Using DbTableModel interface to have a super type for all DbTableModel model = (DbTableModel) table.getModel(); model.add(); } }); GridBagConstraints gbc_btnAdd = new GridBagConstraints(); gbc_btnAdd.insets = new Insets(0, 0, 0, 5); gbc_btnAdd.gridx = 0; gbc_btnAdd.gridy = 2; add(btnAdd, gbc_btnAdd); JButton btnDelete = new JButton("Delete"); btnDelete.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Delete row from current table // Using DbTableModel interface to have a super type for all DbTableModel model = (DbTableModel) table.getModel(); model.delete(table.getSelectedRow()); } }); GridBagConstraints gbc_btnDelete = new GridBagConstraints(); gbc_btnDelete.gridx = 1; gbc_btnDelete.gridy = 2; add(btnDelete, gbc_btnDelete); }
09a4d35d-0f26-4d8b-bbf4-2a07584fd831
4
public boolean OnkoYhteys(Suunta suunta){ switch(suunta){ case Pohjoinen: return OnkoYhteysPohjoiseen(); case Ita: return OnkoYhteysitaan(); case Etela: return OnkoYhteysEtelaan(); case Lansi: return OnkoYhteysLanteen(); } return false; }
038de73c-3b89-403e-ad77-12c24cb5f6e9
2
private final Node<K> buildTree(final Hashtable<K,Integer> distribution) { final TreeSet<Node<K>> forest = new TreeSet<Node<K>>(); for (K key : distribution.keySet()) { forest.add(new Node<K>(key,distribution.get(key))); } while (forest.size()>1) { Node<K> tree0 = forest.first(); forest.remove(tree0); Node<K> tree1 = forest.first(); forest.remove(tree1); Node<K> root = new Node<K>(tree0,tree1); forest.add(root); } return forest.first(); }
933609a8-b808-43fc-ae16-3b72e4c1ac19
4
public static int numDistinct(String S, String T) { int[][] f = new int[S.length() + 1][T.length() + 1]; for (int k = 0; k < S.length(); k++) f[k][0] = 1; for (int i = 1; i <= S.length(); i++) { for (int j = 1; j <= T.length(); j++) { if (S.charAt(i - 1) == T.charAt(j - 1)) { f[i][j] += f[i - 1][j] + f[i - 1][j - 1]; } else { f[i][j] += f[i - 1][j]; } } } return f[S.length()][T.length()]; }
f5f3556c-9166-4a93-911b-0f87627275f7
5
public boolean isColliding(GameObject obj){ //If the left side of this is to the left right side of obj and the right side of this is to the right of the left side of obj if(position.getComponent(0) < obj.position.getComponent(0) + obj.width && this.position.getComponent(0) + this.width > obj.position.getComponent(0)){ //IF the top of this is higher than the bottom of obj and the bottom of this is further down than the top of obj if(position.getComponent(1) < obj.position.getComponent(1) + obj.height && this.position.getComponent(1) + this.height > obj.position.getComponent(1)){ return isRunning() ? getState().isColliding(obj) : true; } } return false; }
61bb5660-2a86-481a-ab53-e4f58e541b0f
3
public void dispatch() { List<StoreLoader<?>> loaders = popLoaders(); for (StoreLoader<?> loader : loaders) { loader.memoryDispatch(rows); } }
079869ad-abfd-4607-9b80-e255e83c8d99
7
protected void handleControlPropertyChanged(final String PROPERTY) { if ("RESIZE".equals(PROPERTY)) { resize(); } else if ("COLOR".equals(PROPERTY)) { led.setStyle("-led-color: " + Util.colorToCss((Color) getSkinnable().getLedColor()) + ";"); changeStyle(); } else if ("STYLE".equals(PROPERTY)) { changeStyle(); } else if ("ON".equals(PROPERTY)) { led.setEffect(getSkinnable().isOn() ? glow : innerShadow); } else if ("FRAME_VISIBLE".equals(PROPERTY)) { frame.setOpacity(getSkinnable().isFrameVisible() ? 1.0 : 0.0); } }
345f6a7b-77e2-4b9d-983a-e637f6e924a4
6
@Override public final void render(Graphics g) { if (hub.DEBUG) { g.setColor(Color.DARK_GRAY); g.drawRect((int) Math.round(x), (int) Math.round(y), (int) Math.round(width), (int) Math.round(height)); } Graphics2D g2d = (Graphics2D) image.get().getGraphics(); g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR, 0.0f)); g2d.fill(new Rectangle2D.Double(0, 0, width, height)); g2d.dispose(); Graphics menuGraphics = image.get().getGraphics(); menuGraphics.setColor(backgroundColour); if (orientation == VERTICAL) menuGraphics.fillRect(0, 0, (int) Math.round(width - (usingScrollBar ? 25 : 0)), (int) Math.round(height)); else if (orientation == HORIZONTAL) menuGraphics.fillRect(0, 0, (int) Math.round(width), (int) Math.round(height - (usingScrollBar ? 25 : 0))); for (TButton button : getTButtons()) button.render(menuGraphics); menuGraphics.dispose(); g.drawImage(image.get(), (int) Math.round(x), (int) Math.round(y), hub.renderer); }
999058d6-0c3f-457c-9d7d-8496fafab1cb
7
static List<Vertex> bfs(Graph g, Vertex start) { if (g == null) { throw new IllegalArgumentException("Input graph must not be null."); } if (start == null) { throw new IllegalArgumentException("Input vertex must not be null."); } final List<Vertex> returnList = new LinkedList<Vertex>(); final Queue<Vertex> toVisit = new LinkedList<Vertex>(); toVisit.add(start); while (!toVisit.isEmpty()) { final Vertex currentVertex = toVisit.remove(); returnList.add(currentVertex); final List<Edge> edges = g.adjacencyList.get(currentVertex); if (edges != null) { for (final Edge e : edges) { if (!returnList.contains(e.y) && !toVisit.contains(e.y)) { toVisit.add(e.y); } } } } return returnList; }
bdcadca5-ea3c-41d2-a5b4-bdd3c06a3a4e
6
private Map<?, ?> createObjectContainer(ContainerFactory containerFactory){ if(containerFactory == null) return new JSONObject(); Map<?, ?> m = containerFactory.createObjectContainer(); if(m == null) return new JSONObject(); return m; }
08134e53-299a-486e-a793-5d7890b19dc9
8
public void checkGame() { if (gameDAO == null) { } else if (!gameDAO.getIsRunning()) { } else if ((playerDAO.getAllWerewolves().size() == 0) || (playerDAO.getAllWerewolves().size() > playerDAO .getAllTownspeople().size())) { gameDAO.endGame(); List<Player> aliveList = playerDAO.getAllAlive(); for (int x = 0; x < aliveList.size(); x++) { userDAO.updateHighScore(1, aliveList.get(x).getUserId()); } } else { Game game = gameDAO.getGame(); Date currentDate = new Date(); float timeElapsed = currentDate.getTime() - game.getCreatedDate().getTime(); int numOfcycles = (int) (timeElapsed / game.getDayNightFreq()); if (timeElapsed - ((numOfcycles) * game.getDayNightFreq()) < 51000) { List<Player> players = playerDAO.getAllAlive(); List<String> votesList = new ArrayList<String>(); for (int x = 0; x < players.size(); x++) { if (players.get(x).getVotedAgainst() != null) { votesList.add(players.get(x).getVotedAgainst()); } } String voteOUT = mostVotedFor(votesList); playerDAO.setDead(voteOUT); } } }
a1f29bf8-a025-424f-b0e2-d6a32e404ae7
1
@Override public void componentShown(ComponentEvent e) { if (resizeOnShow) { e.getComponent().setSize(initialWidth, initialHeight); } }
2151bdfc-e30f-4740-ac42-d66a42afed06
0
public YAML(Iterable<String> headers) { this.headers = headers; }
6202314d-8af3-40a4-a0cf-0dda04969d88
9
public void startServer() throws IOException { // Create a UUID for SPP uuid = new UUID("1101", true); // print uuid logString.append("UUID : " + uuid.toString()); logString.append("\n"); // Create the service url connectionString = "btspp://localhost:" + uuid + ";name=Sample SPP Server"; // open server url streamConnNotifier = (StreamConnectionNotifier) Connector.open(connectionString); // Wait for client connection logString.append("\nServer Started. Waiting for clients to connect..."); logString.append("\n"); connection = streamConnNotifier.acceptAndOpen(); RemoteDevice dev = RemoteDevice.getRemoteDevice(connection); logString.append("Remote device address: " + dev.getBluetoothAddress()); logString.append("\n"); logString.append("Remote device name: " + dev.getFriendlyName(true)); logString.append("\n"); // open input stream for spp client InputStream inStream = connection.openInputStream(); stopService = false; String lineRead = ""; // EOF signal to terminal/end connection while (!"EOF".equals(lineRead) && !stopService) { BufferedReader bReader = new BufferedReader(new InputStreamReader( inStream)); lineRead = bReader.readLine(); if (lineRead != null && !stopService) { System.out.println(lineRead); Robot r; try { r = new Robot(); if ("up".equals(lineRead)) { r.keyPress(KeyEvent.VK_UP); r.keyRelease(KeyEvent.VK_UP); } else if ("down".equals(lineRead)) { r.keyPress(KeyEvent.VK_DOWN); r.keyRelease(KeyEvent.VK_DOWN); } else if ("right".equals(lineRead)) { r.keyPress(KeyEvent.VK_RIGHT); r.keyRelease(KeyEvent.VK_RIGHT); } else if ("left".equals(lineRead)) { r.keyPress(KeyEvent.VK_LEFT); r.keyRelease(KeyEvent.VK_LEFT); } } catch (AWTException e) { // TODO Auto-generated catch block logString.append("Server Error : " + e.getMessage()); e.printStackTrace(); } } } logString.append("Server info : Service stopped"); // send response to spp client OutputStream outStream = connection.openOutputStream(); PrintWriter pWriter = new PrintWriter(new OutputStreamWriter(outStream)); pWriter.write("Response String from SPP Server\r\n"); pWriter.flush(); pWriter.close(); streamConnNotifier.close(); }
bf5b8d76-075b-4c47-bcb8-3d480a457b57
0
public OutlineCommentIndicator(OutlinerCellRendererImpl renderer) { super(renderer, GUITreeLoader.reg.getText("tooltip_toggle_comment")); }
99d2217f-ed62-4cc0-9cc9-902ebfbbbf14
0
public long getId() { return Id; }
5ab7632f-3971-40a2-a8d0-29ba0315f351
0
@Test(expected = RuntimeException.class) public void twoInchesIsBetterEightOuncesShouldThrowException(){ ArithmeticQuantity two_in = new ArithmeticQuantity(2, Distance.INCHES); ArithmeticQuantity eight_oz = new ArithmeticQuantity(8, Volume.OUNCE); two_in.isBetter(eight_oz); }
bdc909d2-a4ef-4229-9b21-e36d37b300d5
1
public void visit_d2l(final Instruction inst) { stackHeight -= 2; if (stackHeight < minStackHeight) { minStackHeight = stackHeight; } stackHeight += 2; }
07b834b7-140c-4f33-a780-6c7b711e77b3
8
protected void cacheReturn(String cacheKey, InterceptorChain chain, Method method, Cache cacheAn) throws Throwable { // 获取缓存类型,根据缓存类型不同分别对缓存有不同的操作方式 CacheType cacheType = cacheAn.cacheType(); if (cacheType.equals(CacheType.String)) { super.cacheReturn(cacheKey, chain, method, cacheAn); } else if (cacheType.equals(CacheType.List)) { // 获取该方法欲读取的缓存的 VALUE List<String> cacheValue = null; try { if (cacheAn.reverse()) { cacheValue = cacheDao().zQueryByRank(cacheKey, 0, -1, Order.Desc); } else { cacheValue = cacheDao().zQueryByRank(cacheKey, 0, -1, Order.Asc); } } catch (Exception e) { logger.error("Read Cache error", e); } // 若缓存值不为空,则该方法直接返回缓存里相应的值 if (cacheValue != null && cacheValue.size() > 0) { chain.setReturnValue(cacheValue); logger.debug("Get a value from this cache"); return; } else { logger.debug("Can't get any value from this cache"); } // 执行方法 chain.doChain(); // 获取方法返回值并增加相应缓存 @SuppressWarnings("unchecked") List<String> returnObj = (List<String>) chain.getReturn(); if (returnObj != null) { try { setCache(cacheKey, returnObj, cacheAn.reverse(), cacheAn.cacheTimeout()); logger.debug("Set a new value for this cache"); } catch (Exception e) { logger.error("Set cache error", e); } } else { logger.warn("No value to set for this cache"); } } else { logger.error("The method annotation : CacheType Error!", new RuntimeException( "The method annotation : CacheType Error")); } }
1e0f7ab2-3ebf-46d4-9a07-58370a01f365
4
public MainFrame() throws HeadlessException { // initializing main form super(ZIP_ARCHIVER_V1_0); setMinimumSize(new Dimension(WIDTH_MAIN_FRAME, HEIGHT_MAIN_FRAME)); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setLocationRelativeTo(null); pack(); // creating main menu { setJMenuBar(new MainMenu()); } // initializing of navigation panel { // buttons init btnAdd = new JButton(ADD, new ImageIcon(ADD24_GIF)); btnExtract = new JButton(EXTRACT); btnRemove = new JButton(REMOVE); // //adding buttons to some JPanel, that will contain them buttonsContainer1 = new JPanel(new GridLayout(1, 3, 10, 0)); buttonsContainer1.add(btnExtract); buttonsContainer1.add(btnAdd); buttonsContainer1.add(btnRemove); // adding buttons' panel to navigation panel like 1 element // to provide necessary view pNav = new JPanel(new FlowLayout(FlowLayout.LEFT)); pNav.add(buttonsContainer1); } // initializing of control panel { // text line init txtFilePath = new JTextField(); txtFilePath.setEditable(false); // //buttons init btnBack = new JButton(BACK); btnBack.addMouseListener(new MouseListener() { @Override public void mouseClicked(MouseEvent e) { if (root.getParentFile().getClass() == SystemFile.class) { root = (SystemFile) root.getParentFile(); // MAST USE OBSERVER FOR THIS!!! fileSystemTableModel.setCurrentDir(root); txtFilePath.setText(root.getAbsolutePath()); } else if (root.getParentFile().getClass() == SystemFile.RootSystemFile.class) { // MAST USE OBSERVER FOR THIS!!! fileSystemTableModel.setCurrentDir(new SystemFile.RootSystemFile()); txtFilePath.setText(" "); } // MAST USE OBSERVER FOR THIS!!! tFiles.updateUI(); } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } }); btnFolder = new JButton(FOLDER); btnFolder.setEnabled(false); // //adding buttons and txt field to control panel pControl = new JPanel();//(new FlowLayout(FlowLayout.LEFT)); pControl.setLayout(new BoxLayout(pControl, BoxLayout.X_AXIS)); pControl.add(btnBack); pControl.add(btnFolder); pControl.add(txtFilePath); } // adding components to main form { JPanel managePanel = new JPanel(); managePanel.setLayout(new BoxLayout(managePanel, BoxLayout.Y_AXIS)); managePanel.add(pNav); managePanel.add(pControl); add(managePanel, BorderLayout.NORTH); } // initializing of data table { fileSystemTableModel = new FileSystemTableModel(new SystemFile.RootSystemFile()); tFiles = new JTable(fileSystemTableModel); //написать для каждой колонки разные // styles for DataTable columns & right displaying of information in them tFiles.setDefaultRenderer(fileSystemTableModel.getColumnClass(0), new BandedTableCellRenderer()); tFiles.setDefaultRenderer(fileSystemTableModel.getColumnClass(1), new BandedTableCellRenderer()); tFiles.setDefaultRenderer(fileSystemTableModel.getColumnClass(2), new BandedTableCellRenderer()); // adding mouse listener for table's rows to make file system // when you're clicking on the row(if it's folder), thah you go to that folder tFiles.addMouseListener(new MouseListener() { @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() >= 2) { int rootRow = tFiles.getSelectedRow(); root = (SystemFile) fileSystemTableModel.getValueAt(rootRow, COLUMN_INDEX); if(root != null) { fileSystemTableModel.setCurrentDir(root); tFiles.updateUI(); } txtFilePath.setText(root.getAbsolutePath()); } } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } }); //adding scroll panel to table JScrollPane dataPanel = new JScrollPane(tFiles); // adding to main form add(dataPanel, BorderLayout.CENTER); } // set form visible setVisible(true); }