method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
16fb8950-6bb2-455f-9ad6-01426efdaa70
4
private boolean isOptimal(double[] b, double[] c) { double[] x = primal(); double[] y = dual(); double value = value(); // check that value = cx = yb double value1 = 0.0; for (int j = 0; j < x.length; j++) value1 += c[j] * x[j]; double value2 = 0.0; for (int i = 0; i < y.length; i++) value2 += y[i] * b[i]; if (Math.abs(value - value1) > EPSILON || Math.abs(value - value2) > EPSILON) { StdOut.println("value = " + value + ", cx = " + value1 + ", yb = " + value2); return false; } return true; }
7cfeaf11-67b7-42f3-a6ec-1379fac2e104
5
public static void validate(List<Long> pointToValidate, List<Long> startPoint, List<Long> endPoint) throws SizeNotEqualException, InvalidPointException { int size = pointToValidate.size(); if (size != startPoint.size()) { throw new SizeNotEqualException( "the sizes of pointToValidate and startPoint should be equal"); } if (size != endPoint.size()) { throw new SizeNotEqualException( "the sizes of pointToValidate and endPoint should be equal"); } for (int i = 0; i < size; i += 1) { if (!(startPoint.get(i) <= pointToValidate.get(i) && pointToValidate .get(i) <= endPoint.get(i))) { throw new InvalidPointException("not valid point: " + startPoint.get(i) + " <= " + pointToValidate.get(i) + " <= " + endPoint.get(i)); } } }
ea00ef8c-2751-4a17-a469-dc6b0b1ab4c3
9
protected final java.lang.Object iterateReader(XMLStreamReader toReader, java.lang.Object toObject, XMLFormatType toFormatType) { java.lang.Object loReturn = null; try { while(toReader.hasNext()) { switch(toReader.getEventType()) { case XMLStreamConstants.START_ELEMENT: { int lnAttributeCount = toReader.getAttributeCount(); // Get all of the attributes from this element PropertySet loAttributes = new PropertySet(lnAttributeCount); for (int i=0; i< lnAttributeCount; i++) { loAttributes.put(toReader.getAttributeLocalName(i), toReader.getAttributeValue(i)); } loReturn = startedElement(toReader, toReader.getLocalName(), loAttributes, toObject, toFormatType); if (loReturn != null) { return loReturn; } break; } case XMLStreamConstants.END_ELEMENT: { if (toObject == null || (toObject != null && isEndingElement(toReader.getLocalName(), toObject, toFormatType))) { return toObject; } break; } default: break; } toReader.next(); } } catch (Throwable ex) { Application.getInstance().log(ex); } return loReturn; }
f293ee64-8fc9-4918-a00e-74037098165a
8
public static void main( String[] args ) throws NoSuchFieldException, SecurityException, NoSuchMethodException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, ClassNotFoundException { String stringer = "this is a String called stringer"; // get class from an object Class<? extends String> stringGetClass = stringer.getClass(); // get class from a class name Class<String> stringclass = String.class; // get all accesible methods @SuppressWarnings( "unused" ) Method[] methods = stringclass.getMethods(); // get all declared methods, also non public @SuppressWarnings( "unused" ) Method[] declaredMethods = stringGetClass.getDeclaredMethods(); // gets a specific method @SuppressWarnings( "unused" ) Method equalsMethod = stringGetClass.getMethod( "equalsIgnoreCase", String.class ); // for more info http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/Modifier.html int modifiers = stringGetClass.getModifiers(); // the same for abstract, volatile, etc System.out.println( "is public " + Modifier.isPublic( modifiers ) ); // get all fields stringGetClass.getFields(); // get a declared field, the class String has no public fields stringGetClass.getDeclaredField( "hash" ); // get all visible constructors Constructor<?>[] constructors = stringGetClass.getConstructors(); // all constructors Constructor<?>[] declaredConstructors = stringclass.getDeclaredConstructors(); System.out.println( "number of visible constructors " + constructors.length ); System.out.println( "number of total constructors " + declaredConstructors.length ); for( Constructor<?> constructor : constructors ) { int numberParams = constructor.getParameterCount(); System.out.println( "constructor " + constructor.getName() ); System.out.println( "number of arguments " + numberParams ); // public, private, etc. int modifiersConstructor = constructor.getModifiers(); System.out.println( "modifiers " + modifiersConstructor ); // array of parameters, more info in the methods section @SuppressWarnings( "unused" ) Parameter[] parameters = constructor.getParameters(); // annotations array, more info in the annotations section @SuppressWarnings( "unused" ) Annotation[] annotations = constructor.getAnnotations(); if( numberParams == 0 ) { // can be used to create new instances @SuppressWarnings( "unused" ) String danibuizaString = (String)constructor.newInstance(); } } // gets the canonical name System.out.println( "canonical name " + stringGetClass.getCanonicalName() ); // get the component type @SuppressWarnings( "unused" ) Class<?> componentType = stringGetClass.getComponentType(); // get the type name String typename = stringGetClass.getTypeName(); System.out.println( "type name " + typename ); // returns true if the object is instance of the class, false otherwise stringGetClass.isInstance( "dani" ); // checks if the object is of a primitive type, in this case, not stringGetClass.isPrimitive(); Class<?> enclosingClass = stringGetClass.getEnclosingClass(); System.out.println( "enclosing class " + enclosingClass ); // it is possible to create instance at runtime @SuppressWarnings( "unused" ) String newInstanceStringClass = stringclass.newInstance(); @SuppressWarnings( "unused" ) String otherInstance = (String)Class.forName( "java.lang.String" ).newInstance(); }
2fb5225f-b51d-4dde-9186-7e651f0a895a
1
public void setCodigo(String codigo) { this.codigo = codigo.isEmpty() ? "sem código" : codigo; }
bcd6d959-9372-49ad-a06d-4b02cdc2a9e3
4
public void run(){ try { buff = new byte[Optiums.BUFF_SIZE]; recordFile = new FileOutputStream(new File(Optiums.FILE_RECORD_NAME + "." + Optiums.FILE_TYPE.toString().toLowerCase())); outpuStream = new OutputStream() { private byte l = 0; private int buffFill = 0; @Override public void write(int arg0) throws IOException { // TODO Auto-generated method stub if(m_line.isRunning()){ recordFile.write(arg0); buff[buffFill] = (byte) arg0; buffFill++; } if(buffFill == Optiums.BUFF_SIZE - 1){ /* Work faster than class Player function update. That is why diagrams of same files can have little differences.*/ interf.updateDiagram(buff); buffFill = 0; } if(l < 24){ recordFile.write(arg0); // Write magic numbers l++; } } }; AudioSystem.write(m_audioInputStream, Optiums.FILE_TYPE, outpuStream); // There will be error if use the Wave format } catch (IOException e) { e.printStackTrace(); } }
a625504b-c458-466c-8806-1738ca5c0888
7
@SuppressWarnings("unchecked") public void registerListener( EventListener listener, Plugin plugin ) { List< Method > methods = new ArrayList< Method >(); Collections.addAll( methods, listener.getClass().getMethods() ); for( Method method : methods ) { EventHandler handler = method.getAnnotation( EventHandler.class ); if( handler == null ) { continue; } Class< ? >[] parameters = method.getParameterTypes(); if( parameters.length != 1 ) { continue; } Class< ? extends Event> eventClass = ( Class<? extends Event> ) parameters[ 0 ]; EventExecutor executor = new EventExecutor( plugin, listener, handler, method ); List< EventExecutor > ex = null; if( executors.containsKey( eventClass ) ) { ex = executors.get( eventClass ); } else { ex = new ArrayList< EventExecutor >(); } ex.add( executor ); executors.put( eventClass, ex ); } }
a98e0482-b0d4-4c86-a371-c5e993f0d82f
5
public void DFS(int a,int b){ Stack<Node> s= new Stack<Node>(); ArrayList<Integer> visited= new ArrayList<Integer>(); Node src=new Node(a); Node dest= new Node(b); s.push(src); while(!s.empty()){ Node tmp=s.pop(); if(!visited.contains(new Integer(tmp.getData()))){ System.out.println(tmp.getData()); visited.add(new Integer(tmp.getData())); ArrayList<Edge> etemp=adjacenyList.get(tmp); if(etemp!=null){ for(Edge edge:etemp){ if(visited.contains(new Integer(edge.getVertex().getData()))){ continue; } s.push(edge.getVertex()); } } } } }
0c1c4117-bb51-4800-9140-5ef172fb006c
5
private final void sendObjectPlacement(final MapleCharacter c) { if (c == null) { return; } for (final MapleMapObject o : getAllMonster()) { updateMonsterController((MapleMonster) o); } for (final MapleMapObject o : getMapObjectsInRange(c.getPosition(), GameConstants.maxViewRangeSq(), GameConstants.rangedMapobjectTypes)) { if (o.getType() == MapleMapObjectType.REACTOR) { if (!((MapleReactor) o).isAlive()) { continue; } } o.sendSpawnData(c.getClient()); c.addVisibleMapObject(o); } }
c6c67830-fda2-4c1e-9909-c56201dc917b
7
public void criaUSER(Usuario user) throws SQLException { Connection conexao = null; PreparedStatement comando = null; try { conexao = BancoDadosUtil.getConnection(); if ("Diretor".equals(user.getTipo())) { comando = conexao.prepareStatement(SQL_INSERT_DIRETOR); } else { comando = conexao.prepareStatement(SQL_INSERT_USUARIO); comando.setString(5, user.getDepartamento().getCodigo()); } comando.setString(1, user.getNome()); comando.setString(2, user.getTipo()); comando.setString(3, user.getSenha()); comando.setString(4, user.getEmail()); comando.execute(); conexao.commit(); } catch (Exception e) { if (conexao != null) { conexao.rollback(); } throw new RuntimeException(e); } finally { if (comando != null && !comando.isClosed()) { comando.close(); } if (conexao != null && !conexao.isClosed()) { conexao.close(); } } }
80ebbb46-b8e8-42ac-ad0f-e18681ffd944
6
private void findNextElement() { try { if(parser.getElement() != null && parser.getElement().hasChildren()) parser.down(); while(true) { parser.next(); if(parser.getElement() != null) { foundNext = true; return; } else { if(parser.getDepth() == 0) { foundNext = false; return; } else { parser.up(); } } } } catch (ParsingException e) { throw new RuntimeException(e); } }
22fed56f-dcf4-4bcd-93dc-31330604f464
8
public void initialize(final ClientDavInterface connection) throws Exception { DataModel dataModel = connection.getDataModel(); ConfigurationAuthority configurationAuthority = null; if(_kv != null && _kv.length() != 0) { try { long id = Long.parseLong(_kv); SystemObject object = dataModel.getObject(id); if(object instanceof ConfigurationAuthority) { configurationAuthority = (ConfigurationAuthority) object; } else if(object == null) { System.err.println("Der angegebene Konfigurationsverantwortliche mit der id " + id + " wurde nicht gefunden."); System.exit(2); } else { System.err.println("Das angegebene Objekt " + object.getPid() + " ist kein Konfigurationsverantwortlicher."); System.exit(2); } } catch(NumberFormatException ignored){ String pid = _kv; SystemObject object = dataModel.getObject(pid); if(object instanceof ConfigurationAuthority) { configurationAuthority = (ConfigurationAuthority) object; } else if(object == null) { System.err.println("Der angegebene Konfigurationsverantwortliche mit der pid " + pid + " wurde nicht gefunden."); System.exit(2); } else { System.err.println("Das angegebene Objekt " + object.getPid() + " ist kein Konfigurationsverantwortlicher."); System.exit(2); } } } System.out.println("Sicherungsvorgang gestartet..."); if(_kv != null){ System.out.println("Konfigurationsverantwortlicher: " + _kv); } dataModel.backupConfigurationFiles(_targetDir, configurationAuthority, new Callback()); System.out.println("Sicherungsvorgang beendet."); }
446195cf-ec14-4616-bd04-e64c7c898ff4
5
private void handleFailed() { uncompletedCount = 0; completedCount = 0; for (OnDemandData onDemandData = (OnDemandData) requested.peekLast(); onDemandData != null; onDemandData = (OnDemandData) requested .reverseGetNext()) if (onDemandData.incomplete) uncompletedCount++; else completedCount++; while (uncompletedCount < 10) { OnDemandData onDemandData_1 = (OnDemandData) aClass19_1368 .popHead(); if (onDemandData_1 == null) break; if (filePriorities[onDemandData_1.dataType][onDemandData_1.id] != 0) filesLoaded++; filePriorities[onDemandData_1.dataType][onDemandData_1.id] = 0; requested.insertHead(onDemandData_1); uncompletedCount++; closeRequest(onDemandData_1); waiting = true; } }
fd681fab-4477-412b-ac38-069899d3e6ba
7
public void log( Level level, String trace, String msg ) { // Forward the call the the default logger super.log( level, trace, msg ); // Then add the event to the HTTPD statistics if( level.equals(Level.SEVERE) ) { this.getHandler().getRuntimeStatistics().reportSevere(); } else if( level.equals(Level.WARNING) ) { this.getHandler().getRuntimeStatistics().reportWarning(); } else if( level.equals(Level.INFO) ) { this.getHandler().getRuntimeStatistics().reportInfo(); } else if( level.equals(Level.CONFIG) ) { this.getHandler().getRuntimeStatistics().reportConfig(); } else if( level.equals(Level.FINE) ) { this.getHandler().getRuntimeStatistics().reportFine(); } else if( level.equals(Level.FINER) ) { this.getHandler().getRuntimeStatistics().reportFiner(); } else if( level.equals(Level.FINEST) ) { this.getHandler().getRuntimeStatistics().reportFinest(); } }
6af9f1d0-4cde-43e1-84c9-f1a4b27a6fb5
4
public static void saveFile(String file, String data, boolean append) throws IOException { BufferedWriter bw = null; OutputStreamWriter osw = null; File f = new File(file); FileOutputStream fos = new FileOutputStream(f, append); try { // write UTF8 BOM mark if file is empty if (f.length() < 1) { final byte[] bom = new byte[] { (byte)0xEF, (byte)0xBB, (byte)0xBF }; fos.write(bom); } osw = new OutputStreamWriter(fos, "UTF-8"); bw = new BufferedWriter(osw); if (data != null) bw.write(data); } catch (IOException ex) { throw ex; } finally { try { bw.close(); fos.close(); } catch (Exception ex) { } } }
2e570732-1eb0-45d3-8845-0aea11e87068
3
@Override public double getTip() { double tip = 0.00; // always initialize local variables switch(serviceQuality) { case GOOD: tip = baseTipPerBag * bagCount * (1 + goodRate); break; case FAIR: tip = baseTipPerBag * bagCount * (1 + fairRate); break; case POOR: tip = baseTipPerBag * bagCount * (1 + poorRate); break; } return tip; }
2982205b-77e5-4382-8351-1fb7a0a71b2e
2
public Collection<String> getClassificacao(String cod_competicao) { try { Collection<String> col = new ArrayList<String>(); Statement stm = conn.createStatement(); ResultSet rs = stm.executeQuery("select Jogador.nome,equipa.cod_equipa as Equipa,golo from Jogador,Marcadores,Equipa where cod_competicao='" + cod_competicao + "'and Jogador.cod_jogador=marcadores.cod_jogador and equipa.cod_equipa=jogador.cod_equipa and golo>0 Order by golo desc "); for (; rs.next();) { col.add((rs.getString(1) + "_" + rs.getString(2) + "_" + rs.getString(3))); } rs.close(); stm.close(); return col; } catch (SQLException | NumberFormatException e) { JOptionPane.showMessageDialog(null, e.getMessage(), "ERROR", JOptionPane.ERROR_MESSAGE); return null; } }
9d65be22-8d04-49a1-bdb8-baa44972032d
4
public static final void setPrintStream(PrintStream stream) { if (!Debug.DEV_MODE) { if (stream == null) { stream = System.out; } if (OUT != stream && OUT != System.out) { OUT.close(); } OUT = stream; } }
c98d6f87-8496-47ca-a4be-9aeec1121c09
7
public static void recCall(int num) { LinkedList<Integer> queue = new LinkedList<Integer>(); queue.add(num); queue.add(-1); Hashtable<Integer, ArrayList<Integer>> memo = new Hashtable<Integer, ArrayList<Integer>>(); boolean firstPlayerTurn = true; while (!queue.isEmpty()) { Integer currNum = queue.poll(); if (currNum == -1) { firstPlayerTurn = !firstPlayerTurn; continue; } ArrayList<Integer> successors = memo.get(currNum); if (successors == null) { successors = generateSuccessors(currNum); memo.put(currNum, successors); } if (successors.size() == 0) { whoWon(firstPlayerTurn); return; } else { for (Integer successor : successors) { if (isPowerOfTwo(successor + 1)) { whoWon(!firstPlayerTurn); return; } if (!queue.contains(successor)) queue.add(successor); } queue.add(-1); } } }
b36d5f03-8c20-4f22-af43-c54fec1f7332
1
public void wdgmsg(Widget sender, String msg, Object... args) { if (sender == cbtn) { clbk.result(false); close(); return; } super.wdgmsg(sender, msg, args); }
b502ba06-a0c3-4caa-90ab-468badad089d
4
public final Action[] createDefaultFontFaceActions() { String[] families = GraphicsEnvironment.getLocalGraphicsEnvironment() .getAvailableFontFamilyNames(); Map fontFamilyRange = Collections.synchronizedMap(new HashMap()); Action a = null; for (int i = 0; i < families.length; i++) { if (families[i].indexOf(".") == -1) { a = this.getFontFaceAction(families[i]); fontFamilyRange.put(families[i], a); } } Action[] output = new Action[fontFamilyRange.size()]; for (int i = 0; i < output.length; i++) { if (families[i].indexOf(".") == -1) { output[i] = (Action) fontFamilyRange.get(families[i]); } } return output; }
877686ae-49d7-4a40-b4a9-8cd0f39f0311
7
public String[] getOptions() { Vector<String> result; result = new Vector<String>(); result.add("-mean-prec"); result.add("" + getMeanPrec()); result.add("-stddev-prec"); result.add("" + getStdDevPrec()); result.add("-col-name-width"); result.add("" + getColNameWidth()); result.add("-row-name-width"); result.add("" + getRowNameWidth()); result.add("-mean-width"); result.add("" + getMeanWidth()); result.add("-stddev-width"); result.add("" + getStdDevWidth()); result.add("-sig-width"); result.add("" + getSignificanceWidth()); result.add("-count-width"); result.add("" + getCountWidth()); if (getShowStdDev()) result.add("-show-stddev"); if (getShowAverage()) result.add("-show-avg"); if (getRemoveFilterName()) result.add("-remove-filter"); if (getPrintColNames()) result.add("-print-col-names"); if (getPrintRowNames()) result.add("-print-row-names"); if (getEnumerateColNames()) result.add("-enum-col-names"); if (getEnumerateRowNames()) result.add("-enum-row-names"); return result.toArray(new String[result.size()]); }
83b5dd7b-fcd6-4137-bcb5-a5797158f186
8
private static float getUnitFactor(String unit) { //byte scale if(unit.equals("KB")) return 1/1024; if(unit.equals("MB")) return 1; if(unit.equals("GB")) return 1024; if(unit.equals("TB")) return 1024 * 1024 ; //freq scale if(unit.equals("Hz")) return 1; if(unit.equals("KHz")) return 1000; if(unit.equals("MHz")) return 1000*1000; if(unit.equals("GHz")) return 1000*1000*1000; return 1f; }
0b375c55-fe56-48fe-9198-939196ac3b97
6
public static int[] selectionSort(int[] array, boolean ascendingOrder) { if (array != null && array.length > 1) { int lengthLessOne = array.length - 1; int minValue; int minIndex; for (int i = 0; i < lengthLessOne; i++) { minValue = array[i]; minIndex = i; for (int j = i + 1; j < array.length; j++) { if (Utils.compareOrder(minValue, array[j], ascendingOrder) == false) { minValue = array[j]; minIndex = j; } } if (minIndex != i) { Utils.swap(array, i, minIndex); } } } return array; }
e5aa0288-8846-4e54-acc1-12e8c888635e
3
@Override public V merge( final K key, final V value, final BiFunction<? super V, ? super V, ? extends V> remappingFunction) { throw new UnsupportedOperationException(); }
351a6196-9e6a-44cf-8c51-e73e11b3b03f
8
public void renderPlayer(int xp, int yp, Sprite sprite) { xp -= xOffset; yp -= yOffset; for(int y = 0; y < 32; y++) { int ya = y + yp; for(int x = 0; x < 32; x++) { int xa = x + xp; if(xa < -32 || xa >= width || ya < 0 || ya >= height) break; if(xa < 0) xa = 0; int col = sprite.pixels[x + y * 32]; if(col != 0xffffff) { pixels[xa + ya * width] = col; } } } }
47cb63b1-8922-47fe-b9cf-6607179346c2
8
public static Map<String, CyIdentifiable> getPDBChains(String queryString, Map<String, CyIdentifiable>reverseMap, Map<CyIdentifiable, List<PDBStructure>>chainMap) throws Exception{ Map<String, CyIdentifiable> newReverseMap = new HashMap<String, CyIdentifiable>(); Map<String, PDBStructure> structureMap = new HashMap<String, PDBStructure>(); URL url = new URL(RCSB_DESCRIBE+"?"+queryString); // System.out.println("Querying "+RCSB_DESCRIBE+" with query: \n-->"+queryString); Pattern r = Pattern.compile("<chain id=\"([A-Z])\""); Pattern s = Pattern.compile("<structureId id=\"(.*?)\""); String structure = null; HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setDoOutput(false); con.setDoInput(true); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String line; while ((line = in.readLine()) != null) { // System.out.println("DESCRIBE line from RCSB: "+line); Matcher mr = r.matcher(line); Matcher ms = s.matcher(line); String chain = null; if (ms.find()) structure = ms.group(1); if (mr.find()) chain = mr.group(1); if (structure != null && chain != null) { // System.out.println("Id for "+structure); CyIdentifiable id = reverseMap.get(structure); // System.out.println("Adding "+structure+"."+chain+" to id "+id.toString()); newReverseMap.put(structure+"."+chain, id); if (!chainMap.containsKey(id)) chainMap.put(id, new ArrayList<PDBStructure>()); if (!structureMap.containsKey(structure)) structureMap.put(structure, new PDBStructure(structure, null)); structureMap.get(structure).addChain(chain); if (!chainMap.get(id).contains(structureMap.get(structure))) chainMap.get(id).add(structureMap.get(structure)); } } in.close(); return newReverseMap; }
352b0854-8a8a-4424-8fac-85c45b955578
3
@Test public void testDrawWorld() { Cell[][] cells = new Cell[][]{ {Cell.LIVING, Cell.DEAD}, {Cell.DEAD, Cell.LIVING}, }; Integer numberOfLivingCells = 0; Integer numberOfDeadCells = 0; for (int i = 0; i < cells.length; i++) { for (int j = 0; j < cells[i].length; j++) { if (cells[i][j] == Cell.LIVING) { numberOfLivingCells++; } else { numberOfDeadCells++; } } } World world = worldFactory.createWorld(cells); universe.setWorld(world); WorldViewerPanel viewerPanel = panelFactory.createWorldViewerPanel(universe); GraphicsMock g = new GraphicsMock(); viewerPanel.paintComponent(g); Color living = viewerPanel.getLivingColor(); assertEquals("The number of drawn living cells should equal the number of living cells", numberOfLivingCells, g.getColorMap().get(living)); // Should not throw error on null Graphics viewerPanel.paintComponent(null); }
877b9221-b6f3-4428-bf76-e3c9e95184d6
1
public void cmpl(final Type type) { mv.visitInsn(type == Type.FLOAT_TYPE ? Opcodes.FCMPL : Opcodes.DCMPL); }
2d10756c-cab3-45a6-9326-af28a22d1e71
2
@Override public boolean takePoints(String name, int points) { if(getPoints(name)<points){ return false; } try { PointsAPI.modifyPointsToPlayer(name, points, Type.RemovePoints); } catch (Exception e) { return false; } return true; }
4f0c9065-d55f-449e-ab18-1ac487818ce7
3
public List<Element> getNodes(String xpath) { try { XPathFactory xpathfactory = XPathFactory.newInstance(); XPath xPath = xpathfactory.newXPath(); XPathExpression expr = xPath.compile(xpath); Object result = expr.evaluate(domNode, XPathConstants.NODESET); if (result != null) { NodeList nodeList = (NodeList) result; List<Element> list = new ArrayList<>(); for (int i = 0; i < nodeList.getLength(); i++) { list.add(new Element(nodeList.item(i))); } return list; } else { return XMLReader.EMPTY_NODE_LIST; } } catch (XPathExpressionException ex) { ex.printStackTrace(); return XMLReader.EMPTY_NODE_LIST; } }
a5086eee-a2b2-4cfa-9732-45ccc1bfaa53
0
public String getName() { return name; }
18094c3a-46ec-43b4-b8c0-a989a5765645
1
private void LoadContent() { try { URL moonLanderMenuImgUrl = this.getClass().getResource("/raceresources/resources/images/stardust.png"); moonLanderMenuImg = ImageIO.read(moonLanderMenuImgUrl); } catch (IOException ex) { Logger.getLogger(Framework.class.getName()).log(Level.SEVERE, null, ex); } }
0a8d8571-6e9b-48a1-be93-3f8587e4eecd
6
@Override public void run() { while(!stop && !hasStopped()) { redirectStdin(); redirectStdout(); try { for(String s : getEvents()) { EventHandler.handle(new Event(s)); } } catch (Exception e) { e.printStackTrace(); } try { sleep(100); } catch(InterruptedException e) {} } // If the server did not stop, KILL IT. if(!hasStopped()) forceStop(); }
3115bd55-e520-4d30-8c32-080bcc3276f6
2
public static Date[] getColumnDateValues(CSTable t, String columnName) { int col = columnIndex(t, columnName); if (col == -1) { throw new IllegalArgumentException("No such column: " + columnName); } Conversions.Params p = new Conversions.Params(); p.add(String.class, Date.class, lookupDateFormat(t, col)); List<Date> l = new ArrayList<Date>(); for (String[] s : t.rows()) { l.add(Conversions.convert(s[col], Date.class, p)); } return l.toArray(new Date[0]); }
0edd2449-a870-4bfc-a8d2-3b550088c6db
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(RegistroViajes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(RegistroViajes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(RegistroViajes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(RegistroViajes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new RegistroViajes().setVisible(true); } }); }
6cde54a7-26a1-44d2-95cc-4278d547f0c9
9
private void iniciaRodada() { criaPecas(); int n = distribuiPecas(); pontaDir = pontaEsq = n; int i = prim; vez = i % 4; turno = 0; while (vencedor == 5) { vez = i % 4; for (int j = 0; j < jogadores.length; j++) { jogadores[j].recebeMsg(codificaDados(1)); jogadores[j].recebeMsg(codificaDados(6)); } jogadores[vez].recebeMsg("739"); i++; turno++; } if (vencedor < 3) { if (pontaDir == pontaEsq) { if (ultimaJogada[vencedor].getDir() == ultimaJogada[vencedor].getEsq()) { pontuacaoA += 4; } else { pontuacaoA += 3; } } else if (ultimaJogada[vencedor].getDir() == ultimaJogada[vencedor].getEsq()) { pontuacaoA += 2; } else { pontuacaoA++; } } else { if (pontaDir == pontaEsq) { if (ultimaJogada[vencedor].getDir() == ultimaJogada[vencedor].getEsq()) { pontuacaoB += 4; } else { pontuacaoB += 3; } } else if (ultimaJogada[vencedor].getDir() == ultimaJogada[vencedor].getEsq()) { pontuacaoB += 2; } else { pontuacaoB++; } } }
681f668f-8759-4e8a-88b7-7f894f2059f6
0
private void ok() { this.styleName = (File) styles.getSelectedItem(); this.shouldProceed = true; hide(); }
6fcc4791-0384-4244-ab36-32000e7a29e9
2
public Item removeFirst() { if (isEmpty()) throw new java.util.NoSuchElementException(); else if (size() == 1) { Item item = first.item; first = null; last = null; size--; return item; } Item item = first.item; first = first.next; first.prev = null; size--; return item; }
0193bac0-aa4e-4a7b-9db4-d72a8fdc9816
1
public SoundData(IAudioDevice device, String fileName) throws IOException { this.device = device; this.id = 0; try { this.id = loadAudio(device, fileName); } catch (UnsupportedAudioFileException e) { throw new IOException(e); } }
6b385194-8019-44a0-86d4-bf189ab6680a
8
private static boolean collapseIfIf(IfNode rtnode) { if (rtnode.edgetypes.get(0) == 0) { IfNode ifbranch = rtnode.succs.get(0); if (ifbranch.succs.size() == 2) { // if-if branch if (ifbranch.succs.get(1).value == rtnode.succs.get(1).value) { IfStatement ifparent = (IfStatement)rtnode.value; IfStatement ifchild = (IfStatement)ifbranch.value; Statement ifinner = ifbranch.succs.get(0).value; if (ifchild.getFirst().getExprents().isEmpty()) { ifparent.getFirst().removeSuccessor(ifparent.getIfEdge()); ifchild.removeSuccessor(ifchild.getAllSuccessorEdges().get(0)); ifparent.getStats().removeWithKey(ifchild.id); if (ifbranch.edgetypes.get(0).intValue() == 1) { // target null ifparent.setIfstat(null); StatEdge ifedge = ifchild.getIfEdge(); ifchild.getFirst().removeSuccessor(ifedge); ifedge.setSource(ifparent.getFirst()); if (ifedge.closure == ifchild) { ifedge.closure = null; } ifparent.getFirst().addSuccessor(ifedge); ifparent.setIfEdge(ifedge); } else { ifchild.getFirst().removeSuccessor(ifchild.getIfEdge()); StatEdge ifedge = new StatEdge(StatEdge.TYPE_REGULAR, ifparent.getFirst(), ifinner); ifparent.getFirst().addSuccessor(ifedge); ifparent.setIfEdge(ifedge); ifparent.setIfstat(ifinner); ifparent.getStats().addWithKey(ifinner, ifinner.id); ifinner.setParent(ifparent); if (!ifinner.getAllSuccessorEdges().isEmpty()) { StatEdge edge = ifinner.getAllSuccessorEdges().get(0); if (edge.closure == ifchild) { edge.closure = null; } } } // merge if conditions IfExprent statexpr = ifparent.getHeadexprent(); List<Exprent> lstOperands = new ArrayList<>(); lstOperands.add(statexpr.getCondition()); lstOperands.add(ifchild.getHeadexprent().getCondition()); statexpr.setCondition(new FunctionExprent(FunctionExprent.FUNCTION_CADD, lstOperands, null)); statexpr.addBytecodeOffsets(ifchild.getHeadexprent().bytecode); return true; } } } } return false; }
4f75255b-1aaa-463c-be52-bfe8a3608c4f
1
public void deleteClientInfo(String t_name) { ClientInfo temp = this.find(t_name); if (temp != null) client_list.remove(temp); }
ea7f12a1-02d6-4ece-8ac8-c4678e19e2ea
8
@Override public void mouseClicked(int button, int x, int y, int clickcount) { Client.debug("clicked in a window x:" + x + " y:" + y ); boolean found = false; for (GUIObject obj : objects.values()) { if (!obj.isInput()) continue; if ( x >= obj.getRealX() && x < obj.getRealX()+obj.getRealWidth() ) { if ( y >= obj.getRealY() && y < obj.getRealY()+obj.getRealHeight() ) { found = true; Client.debug("Clicked " + obj.getName()); obj.mouseClicked(button, x-obj.getRealX(), y-obj.getRealY(), clickcount); break; } } } if (!found) { if (selected != null) { selected.setSelected(false); selected = null; } } }
8021e3aa-6168-46e4-b7f5-9d4a4c8ab7e2
9
protected void btnSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalvarActionPerformed if(JOptionPane.showConfirmDialog(rootPane, "Você tem certeza que deseja Salvar ?")== 0){ if(txtNome.getText().isEmpty()){ JOptionPane.showMessageDialog(rootPane, "O campo nome não pode ser Vazio !"); }else if(txtNome.getText().length() < 3 || txtNome.getText().length() > 255){ JOptionPane.showMessageDialog(rootPane,"Informe um nome maior 3 caracteres e mennor que 255 caracteres !"); }else if(Double.parseDouble(txtValorCompra.getText()) <=0){ JOptionPane.showMessageDialog(rootPane, "O valor No campo Valor de Compra Não pode ser Menor ou igual a zero !"); }else{ Produto novo = new Produto(); Estoque novoEstoque = new Estoque(); novo.setEstoque(novoEstoque); novo.setDescricao(TxtAreaDescricao.getText()); try { novo.setNome(txtNome.getText()); novo.setValorUnidadeCompra(Double.parseDouble(txtValorCompra.getText())); novo.setValorUnidadeVenda(Double.parseDouble(txtValorUnitario.getText())); novo.setId(this.idProduto); novoEstoque.setQuantidade(Integer.parseInt(txtQuantidade.getText())); novoEstoque.setId(this.idProduto); } catch (ErroValidacaoException | NumberFormatException ex){ //Logger.getLogger(frmCadastroProduto.class.getName()).log(Level.SEVERE, null, ex); JOptionPane.showMessageDialog(rootPane, ex); novo = null; } if(novo != null){ ProdutoDAO dao = new ProdutoDAO(); if(dao.Salvar(novo)){ JOptionPane.showMessageDialog(rootPane, "salvo"); TxtAreaDescricao.setText(""); txtNome.setText(""); txtQuantidade.setText(""); txtValorCompra.setText(""); txtValorUnitario.setText(""); JOptionPane.showMessageDialog(rootPane, "Salvo com sucesso !"); if(edicao){ this.dispose(); } } }else{ JOptionPane.showMessageDialog(rootPane, " não salvo"); } } } }//GEN-LAST:event_btnSalvarActionPerformed
be1ed625-5f41-49c5-9bbd-10b071190890
0
public void setId(String id) { this.id = id; setDirty(); }
820ee708-069f-43ce-ab32-0eb543e63b6e
1
public JavaFileManagerClassLoader(JavaFileManager fileManager, final ClassLoader parent) { super(parent); if (fileManager == null) { throw new NullPointerException("fileManager"); } this.fileManager = fileManager; }
4bc9fd10-a134-41c9-973c-53727616d568
4
public void keyPressed(KeyEvent e) { int i = targetList.getSelectedIndex(); switch (e.getKeyCode()) { case KeyEvent.VK_UP: i = targetList.getSelectedIndex() - 1; if (i < 0) { i = 0; } targetList.setSelectedIndex(i); break; case KeyEvent.VK_DOWN: int listSize = targetList.getModel().getSize(); i = targetList.getSelectedIndex() + 1; if (i >= listSize) { i = listSize - 1; } targetList.setSelectedIndex(i); break; default: break; } }
7fa3ebd6-27b3-4d30-8cb5-6be4f5a37ba4
6
private static void findPairIntersections() { for (Pair p1 : values) { Card[] c1 = p1.cards; int i1 = p1.ordinal; for (Pair p2 : values) { int i2 = p1.ordinal; Card[] c2 = p2.cards; intersectsPair[i1][i2] = false; if(c1[0] == c2[0]) intersectsPair[i1][i2] = true; if(c1[0] == c2[1]) intersectsPair[i1][i2] = true; if(c1[1] == c2[0]) intersectsPair[i1][i2] = true; if(c1[1] == c2[1]) intersectsPair[i1][i2] = true; } } }
58660590-5c18-4791-aed1-02bba728a90f
0
public void updatePacketTime(int packetTime) { lastPacketTime = packetTime; }
60b320b5-3001-4bb4-8a75-c45224fcdc54
4
public Component getTreeCellRendererComponent( JTree tree,Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { // Allow the original renderer to set up the label Component c = super.getTreeCellRendererComponent( tree, value, selected, expanded, leaf, row, hasFocus); DefaultMutableTreeNode node = (DefaultMutableTreeNode)value; if (node.getUserObject() instanceof Asset) { Asset task = (Asset)node.getUserObject(); setText(task.getName()); } if (node.getUserObject() instanceof Task) { Task task = (Task)node.getUserObject(); setText(task.getTaskName()); } if (node.getUserObject() instanceof Element) { Element task = (Element)node.getUserObject(); setText(task.getName()); } if (node.getUserObject() instanceof Project) { Project project = (Project)node.getUserObject(); setText(project.getProjectName()); } return this; }
96e406d4-759b-4cff-a0ca-d121f88342fb
6
public static int spawn_in_out_err(String command, String infile, String outfile, String errfile) { Process p; try { p = Runtime.getRuntime().exec(command); } catch (IOException e) { return -1; } try { if (infile != null) { (new Xfer(new FileInputStream(infile), p.getOutputStream())).start(); } if (outfile != null) { (new Xfer(p.getInputStream(), new FileOutputStream(outfile))).start(); } if (errfile != null) { (new Xfer(p.getErrorStream(), new FileOutputStream(errfile))).start(); } return p.waitFor(); } catch (FileNotFoundException e) { return -2; } catch (InterruptedException e) { return -4; } }
10887e19-4aba-4bdd-acf5-2ad35d4a67e9
4
public void rotate(int[][] matrix) { int length = matrix.length; int[][] array = new int[length][length]; for(int i =0;i < length;i++){ for(int j =0;j<length;j++){ array[j][length-1-i] = matrix[i][j] ; } } for(int i =0;i < length;i++){ for(int j =0;j<length;j++){ matrix[i][j] =array[i][j]; } } }
0fdf4f28-32dd-4397-9719-ecfa984fee23
0
@Override public String toString() { return this.def + "@" + this.key; }
89148799-8785-427c-8c9c-16596745141c
3
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("username"); String password = request.getParameter("password"); List<User> list = DB.getAll(); for(User user : list){ if(user.getUsername().equals(username)&&user.getPassword().equals(password)){ request.getSession().setAttribute("user", user); response.sendRedirect("/myday07/index.jsp"); return; } } response.setContentType("text/html;charset=UTF-8"); response.setCharacterEncoding("UTF-8"); response.getWriter().write("账号或密码错误!"); }
dc889507-e6e3-41c8-a91f-5b5f5fa60150
2
private TeamMember findPlayer(String name, String number, TeamMember defaultReturn) { TeamMember playerToFind = new Player(name, "Team", number, "age"); for (Player player : players) { if (player.equals(playerToFind)){ return player; } } return defaultReturn; }
b7fc17c1-0994-4dae-87cf-bced0df0faf6
9
public static final void main(String[] args) throws Exception { if(args.length < 1 || args.length > 2) { System.err.println("usage: Ping host [count]"); System.exit(1); } final ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(2); try{ final InetAddress address = InetAddress.getByName(args[0]); final String hostname = address.getCanonicalHostName(); final String hostaddr = address.getHostAddress(); final int count; // Ping programs usually use the process ID for the identifier, // but we can't get it and this is only a demo. final int id = 65535; final Pinger ping; if(args.length == 2) count = Integer.parseInt(args[1]); else count = 5; if(address instanceof Inet6Address) ping = new Ping.PingerIPv6(id); else ping = new Ping.Pinger(id); ping.setEchoReplyListener(new EchoReplyListener() { StringBuffer buffer = new StringBuffer(128); public void notifyEchoReply(ICMPEchoPacket packet, byte[] data, int dataOffset, byte[] srcAddress) throws IOException { long end = System.nanoTime(); long start = OctetConverter.octetsToLong(data, dataOffset); // Note: Java and JNI overhead will be noticeable (100-200 // microseconds) for sub-millisecond transmission times. // The first ping may even show several seconds of delay // because of initial JIT compilation overhead. double rtt = (double)(end - start) / 1e6; buffer.setLength(0); buffer.append(packet.getICMPPacketByteLength()) .append(" bytes from ").append(hostname).append(" ("); buffer.append(InetAddress.getByAddress(srcAddress).toString()); buffer.append("): icmp_seq=") .append(packet.getSequenceNumber()) .append(" ttl=").append(packet.getTTL()).append(" time=") .append(rtt).append(" ms"); System.out.println(buffer.toString()); } }); System.out.println("PING " + hostname + " (" + hostaddr + ") " + ping.getRequestDataLength() + "(" + ping.getRequestPacketLength() + ") bytes of data)."); final CountDownLatch latch = new CountDownLatch(1); executor.scheduleAtFixedRate(new Runnable() { int counter = count; public void run() { try { if(counter > 0) { ping.sendEchoRequest(address); if(counter == count) latch.countDown(); --counter; } else executor.shutdown(); } catch(IOException ioe) { ioe.printStackTrace(); } } }, 0, 1, TimeUnit.SECONDS); // We wait for first ping to be sent because Windows times out // with WSAETIMEDOUT if echo request hasn't been sent first. // POSIX does the right thing and just blocks on the first receive. // An alternative is to bind the socket first, which should allow a // receive to be performed frst on Windows. latch.await(); for(int i = 0; i < count; ++i) ping.receiveEchoReply(); ping.close(); } catch(Exception e) { executor.shutdown(); e.printStackTrace(); } }
1b58a3a7-1b39-42d7-bb58-806a27cba529
7
static void testValidity(Object o) throws JSONException { if (o != null) { if (o instanceof Double) { if (((Double)o).isInfinite() || ((Double)o).isNaN()) { throw new JSONException( "JSON does not allow non-finite numbers."); } } else if (o instanceof Float) { if (((Float)o).isInfinite() || ((Float)o).isNaN()) { throw new JSONException( "JSON does not allow non-finite numbers."); } } } }
99e6092c-bd1f-47b4-804e-acf042d3c92b
0
public void testLastDay() { Date date = new Date(); Date r = DateUtils.getLastDayOfTheMonth(date); System.out.println(r); }
7b93ac44-7224-4720-a44b-212ac10b3dd5
6
void setExampleWidgetForeground () { if (colorAndFontTable == null) return; // user cannot change color/font on this tab Control [] controls = getExampleControls (); if (!instance.startup) { for (int i = 0; i < controls.length; i++) { controls[i].setForeground (foregroundColor); } } /* Set the foreground color item's image to match the foreground color of the example widget(s). */ Color color = foregroundColor; if (controls.length == 0) return; if (color == null) color = controls [0].getForeground (); TableItem item = colorAndFontTable.getItem(FOREGROUND_COLOR); Image oldImage = item.getImage(); if (oldImage != null) oldImage.dispose(); item.setImage (colorImage(color)); }
722f2adc-623b-4394-babb-0c6644fdd476
3
public void loadConfig() { localeFileName = config.getString("locale.filename"); iInterval = config.getInt("interval"); iQuota = config.getInt("quota"); iBreakMax = config.getInt("block-break.max"); iBreakMult = config.getInt("block-break.multiplier"); iPlaceMax = config.getInt("block-place.max"); iPlaceMult = config.getInt("block-place.multiplier"); iTravelMax = config.getInt("blocks-traveled.max"); iTravelMult = config.getInt("blocks-traveled.multiplier"); iChatMax = config.getInt("chat-commands.max"); iChatMult = config.getInt("chat-commands.multiplier"); iAnimalMax = config.getInt("damage-animal.max"); iAnimalMult = config.getInt("damage-animal.multiplier"); iMonsterMax = config.getInt("damage-monster.max"); iMonsterMult = config.getInt("damage-monster.multiplier"); iPlayerMax = config.getInt("damage-player.max"); iPlayerMult = config.getInt("damager-player.multiplier"); useMySQL = config.getBoolean("database.use-mysql"); if (useMySQL) { sqlHostname = config.getString("database.mysql.hostname"); sqlPort = config.getString("database.mysql.port"); sqlUsername = config.getString("database.mysql.username"); sqlPassword = config.getString("database.mysql.password"); sqlDatabase = config.getString("database.mysql.database"); sqlPrefix = config.getString("database.mysql.tableprefix"); sqlURI = constructURI(sqlHostname, sqlPort, sqlDatabase); } ecoMode = config.getString("economy.mode"); ecoMin = config.getDouble("economy.min"); ecoMax = config.getDouble("economy.max"); remotesqlHostname = config.getString("autopromote.mysql.hostname"); useremoteMySQL = remotesqlHostname != null && remotesqlHostname != ""; if( useremoteMySQL ) { remotesqlPort = config.getString("autopromote.mysql..port"); remotesqlUsername = config.getString("autopromote.mysql.username"); remotesqlPassword = config.getString("autopromote.mysql.password"); remotesqlDatabase = config.getString("autopromote.mysql.database"); remotesqlTable = config.getString("autopromote.mysql.tablename"); remotesqlColumn = config.getString("autopromote.mysql.namefield"); remotesqlCondition = config.getString("autopromote.mysql.condition"); remotesqlURI = constructURI(remotesqlHostname, remotesqlPort, remotesqlDatabase); } loadPromoterRanks(); }
cab378c4-731d-490f-98fa-f99526f90155
2
public boolean equals(final Object obj) { return (obj instanceof NameAndType) && ((NameAndType) obj).name.equals(name) && ((NameAndType) obj).type.equals(type); }
5f0718d5-e63a-46a8-9280-416007feb8d1
7
public Boolean estocarNovos(List<Estoque> estoques) { Boolean sucesso = false; if (estoques != null) { Connection connection = conexao.getConnection(); try { String valorDoComandoUm = comandos.get("estocarNovos" + 1); String valorDoComandoDois = comandos.get("estocarNovos" + 2); StringBuilder query = new StringBuilder(valorDoComandoUm); for (int i = 0; i < estoques.size(); i++) { query.append("\n").append(valorDoComandoDois); } connection.setAutoCommit(false); PreparedStatement preparedStatement = connection.prepareStatement(query.toString()); query.delete(0, query.length()); int indice = 1; for (Estoque estoque : estoques) { preparedStatement.setInt(indice++, estoque.getMaterial().getCodigo()); preparedStatement.setString(indice++, estoque.getLocalLogicoFisico()); } preparedStatement.execute(); connection.commit(); connection.setAutoCommit(true); sucesso = true; } catch (SQLException ex) { try { connection.rollback(); } catch (SQLException ex1) { } throw new RuntimeException(ex.getMessage()); } catch (NullPointerException ex) { throw new RuntimeException(ex.getMessage()); } catch (Exception ex) { throw new RuntimeException(ex.getMessage()); } finally { conexao.fecharConnection(); } } return sucesso; }
2bb9a5b4-078f-4bff-9c37-09304b430e2f
1
@Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { setText((value == null) ? "" : value.toString()); return this; }
8a5d58d2-35c5-4639-b447-3887efc937b8
9
@Override public void setValueAt(Object value, final int row, final int col) { final String key = this.propNames.get(row); final WidgetProperty p = this.dataMap.get(key); p.setValue(value); Object o; if ((this.selectedComponents != null) && !this.selectedComponents.isEmpty()) { o = this.selectedComponents.get(0); } else { o = this.form; } try { if (p.getType().equals(int.class) || p.getType().equals(Integer.class)) { value = Integer.parseInt((String) value); } else if (p.getType().isEnum()) { // value = Enum.valueOf(p.getType(), (String)value); } p.getSetter().invoke(o, value); } catch (final IllegalArgumentException e) { } catch (final IllegalAccessException e) { } catch (final InvocationTargetException e) { this.updateDataModel(this.selectedComponents); if (e.getCause() instanceof WidgetNameExistsException) { JOptionPane.showMessageDialog(null, e.getCause().getMessage(), "Error while renaming widget", JOptionPane.ERROR_MESSAGE); } e.printStackTrace(); } final PropertyUpdatedSignal s = new PropertyUpdatedSignal(); s.setSource(this); s.setPropertyName(key); SignalManager.getInstance().sendSignal(s, "propertyEditor"); }
ebd491db-15f7-4774-8ddb-4b1072d4084d
2
public void testGetIntervalConverter() { IntervalConverter c = ConverterManager.getInstance().getIntervalConverter(new Interval(0L, 1000L)); assertEquals(ReadableInterval.class, c.getSupportedType()); c = ConverterManager.getInstance().getIntervalConverter(""); assertEquals(String.class, c.getSupportedType()); c = ConverterManager.getInstance().getIntervalConverter(null); assertEquals(null, c.getSupportedType()); try { ConverterManager.getInstance().getIntervalConverter(Boolean.TRUE); fail(); } catch (IllegalArgumentException ex) {} try { ConverterManager.getInstance().getIntervalConverter(new Long(0)); fail(); } catch (IllegalArgumentException ex) {} }
fcd6f006-5dc4-4936-a3ae-077a3cf33e79
3
public void move() { if (isFalling) { dy = dy+gravity; y += dy; } else { y -= dy; dy = dy+antiGravity; } if (dy < 0.01f) { isFalling = true; dy = 0.02f; } if (y < 0) { isFalling = true; dy = 0.02f; move(); } }
9af181c6-7143-477b-83b7-c7d5fb4f83ee
9
@Override public NfcMessage write(NfcMessage input) throws IOException { if (!isEnabled()) { if (Config.DEBUG) Log.d(TAG, "could not write message, reader is not enabled"); eventHandler.handleMessage(NfcEvent.FATAL_ERROR, NFCTRANSCEIVER_NOT_CONNECTED); return new NfcMessage(Type.ERROR).sequenceNumber(input); } if (!reader.isOpened()) { if (Config.DEBUG) Log.d(TAG, "could not write message, reader is not or no longe open"); eventHandler.handleMessage(NfcEvent.FATAL_ERROR, NFCTRANSCEIVER_NOT_CONNECTED); return new NfcMessage(Type.ERROR).sequenceNumber(input); } final byte[] bytes = input.bytes(); if (bytes.length > MAX_WRITE_LENGTH) { throw new IllegalArgumentException("The message length exceeds the maximum capacity of " + MAX_WRITE_LENGTH + " bytes."); } final byte[] recvBuffer = new byte[MAX_WRITE_LENGTH]; final int length; try { length = reader.transmit(0, bytes, bytes.length, recvBuffer, recvBuffer.length); } catch (ReaderException e) { if (Config.DEBUG) Log.e(TAG, "could not write message - ReaderException", e); eventHandler.handleMessage(NfcEvent.FATAL_ERROR, UNEXPECTED_ERROR); return new NfcMessage(Type.ERROR).sequenceNumber(input); } if (length <= 0) { if (Config.DEBUG) Log.d(TAG, "could not write message - return value is 0"); eventHandler.handleMessage(NfcEvent.FATAL_ERROR, UNEXPECTED_ERROR); return new NfcMessage(Type.ERROR).sequenceNumber(input); } byte[] result = new byte[length]; System.arraycopy(recvBuffer, 0, result, 0, length); return new NfcMessage(result); }
188ff6de-cc2d-4cd3-a57e-46fab69ae3c4
8
public synchronized void sortBy(int dim) { if((dim<1)||(dim>dimensions)) throw new java.lang.IndexOutOfBoundsException(); dim--; if(stuff!=null) { final TreeSet<Object> sorted=new TreeSet<Object>(); Object O=null; for (final Object[] name : stuff) { O=(name)[dim]; if(!sorted.contains(O)) sorted.add(O); } final SVector<Object[]> newStuff = new SVector<Object[]>(stuff.size()); for(final Iterator<Object> i=sorted.iterator();i.hasNext();) { O=i.next(); for (final Object[] Os : stuff) { if(O==Os[dim]) newStuff.addElement(Os); } } stuff=newStuff; } }
f2c01ab3-0627-4c35-97f5-c779b5f58229
7
public void place(int x, int y) { if (this instanceof RockTower &&player.getGold()>=600) { player.addTower(new RockTower(player, player.getTowers().size(), x, y)); player.pay(600); } else if (this instanceof SpikyTower&&player.getGold()>=1000) { player.addTower(new SpikyTower(player, player.getTowers().size(), x, y)); player.pay(1000); } else if (this instanceof ArrowTower&&player.getGold()>=800) { player.addTower(new ArrowTower(player, player.getTowers().size(), x, y)); player.pay(800); } else if(player.getGold()>=1200){ player.addTower(new LightningWizard(player, player.getTowers().size(), x, y)); player.pay(1200); } clicked = false; }
90ef2be2-9b46-4e70-9c21-64313abbcb48
1
public int evaluate (AbstractPlay play, Player cpu, int largestCapture) { int evaluation = evaluateRecursively(play, cpu); if (play.eatNumber() < largestCapture) evaluation--; return evaluation; }
694207e1-77f8-48bd-8c7c-2b7c0d4895c9
4
private boolean precisaAutenticar(String url) { return !url.contains("index.xhtml") && !url.contains("institucional.xhtml") && !url.contains("area-do-cliente.xhtml") && !url.contains("contato.xhtml") && !url.contains("javax.faces.resources"); }
751f2fc2-3ac9-4f0b-8396-10f958fa6829
7
@Override public void run(int interfaceId, int componentId) { if (stage == -1) { stage = 0; sendEntityDialogue( SEND_2_TEXT_CHAT, new String[] { NPCDefinitions.getNPCDefinitions(npcId).name, "You have already learned the first thing needed to", "succeed in this world talking to other people!" }, IS_NPC, npcId, 9827); } else if (stage == 0) { stage = 1; sendEntityDialogue( SEND_3_TEXT_CHAT, new String[] { NPCDefinitions.getNPCDefinitions(npcId).name, "You will find many inhabitants of this world have useful", "things to say to you. By clicking on them with your", "mouse you can talk to them." }, IS_NPC, npcId, 9827); } else if (stage == 1) { stage = 2; sendEntityDialogue( SEND_4_TEXT_CHAT, new String[] { NPCDefinitions.getNPCDefinitions(npcId).name, "I would also suggest reading through some of the", "supporting information on the website. There you can", "find the Knowledge Base, which contains all the.", "additional information you're ever likely to need. It also" }, IS_NPC, npcId, 9827); } else if (stage == 2) { stage = 3; sendEntityDialogue( SEND_2_TEXT_CHAT, new String[] { NPCDefinitions.getNPCDefinitions(npcId).name, "contains maps and helpfull tips to help you on your", "journey." }, IS_NPC, npcId, 9827); } else if (stage == 3) { stage = 4; sendEntityDialogue( SEND_2_TEXT_CHAT, new String[] { NPCDefinitions.getNPCDefinitions(npcId).name, "You will notice a flashing icon of a spanner; please click", "on this to continue the tutorial." }, IS_NPC, npcId, 9827); controler.updateProgress(); } else if (stage == 5) { stage = 6; sendEntityDialogue( SEND_2_TEXT_CHAT, new String[] { NPCDefinitions.getNPCDefinitions(npcId).name, "To continue the tutorial go through that door over", "there and speak to your first instructor!" }, IS_NPC, npcId, 9827); } else if (stage == 6) { controler.updateProgress(); end(); } else end(); }
d13b6b8a-6999-45a4-a59c-20eacf7bcd38
6
public static OS getPlatform() { String osName = System.getProperty("os.name").toLowerCase(); if (osName.contains("win")) { return OS.windows; } if (osName.contains("mac")) { return OS.macos; } if (osName.contains("solaris")) { return OS.solaris; } if (osName.contains("sunos")) { return OS.solaris; } if (osName.contains("linux")) { return OS.linux; } if (osName.contains("unix")) { return OS.linux; } return OS.unknown; }
31ed4572-2dab-4101-a5d2-4ec705b520fe
5
public Export(RSInterface main) { if (main == null) { JOptionPane.showMessageDialog(null, "This is not a valid interface!"); return; } this.main = main; setChildren(); if (layers != null && !layers.isEmpty()) { setSubChildren(); } if (subchildren != null && !subchildren.isEmpty()) { setSubSubChildren(); } export(); }
28a1d1fe-2757-455d-b885-6eb16d97a0fe
0
public void actionPerformed(ActionEvent e) { JComponent c = (JComponent) environment.getActive(); PrintUtilities.printComponent(c); }
ed2b15fa-7b4f-4962-818a-9f56c567c4fb
8
public static Vector2f rectCollide(Vector2f oldPos, Vector2f newPos, Vector2f size1, Vector2f pos2, Vector2f size2) { Vector2f result = new Vector2f(1,1); if(!(newPos.getX() + size1.getX() < pos2.getX() || newPos.getX() - size1.getX() > pos2.getX() + (size2.getX() * size2.getX()) || oldPos.getY() + size1.getY() < pos2.getY() || oldPos.getY() - size1.getY() > pos2.getY() + (size2.getY() * size2.getY()))) result.setX(0); if(!(oldPos.getX() + size1.getX() < pos2.getX() || oldPos.getX() - size1.getX() > pos2.getX() + (size2.getX() * size2.getX()) || newPos.getY() + size1.getY() < pos2.getY() || newPos.getY() - size1.getY() > pos2.getY() + (size2.getY() * size2.getY()))) result.setY(0); return result; }
36435afd-fce2-4f6b-8569-386cd9e336a1
2
@SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanelBusca = new javax.swing.JPanel(); jScrollPane4 = new javax.swing.JScrollPane(); tbProjetos = new javax.swing.JTable(); txtPesquisaProjetos = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jPanelDadosProjetos = new javax.swing.JPanel(); lblNome = new javax.swing.JLabel(); txtNomeProjeto = new javax.swing.JTextField(); lblDescricao = new javax.swing.JLabel(); txtDescricao = new javax.swing.JScrollPane(); txtDescricaoProjeto = new javax.swing.JTextArea(); lblDataInicio = new javax.swing.JLabel(); lblDataTermino = new javax.swing.JLabel(); cbDepartamentos = new javax.swing.JComboBox(); lblDepartamento = new javax.swing.JLabel(); btnSalvarAlteracao = new javax.swing.JButton(); btnExcluir = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); txtCod = new javax.swing.JTextField(); txtDataInicio = new javax.swing.JFormattedTextField(); txtDataTermino = new javax.swing.JFormattedTextField(); btnOK = new javax.swing.JButton(); setClosable(true); setIconifiable(true); setTitle("Gerenciar Projeto"); setFrameIcon(new javax.swing.ImageIcon(getClass().getResource("/br/edu/ifnmg/alvespereira/segurancadados/icones/11295_128x128.png"))); // NOI18N jPanelBusca.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Busca de Projeto", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 12), new java.awt.Color(0, 102, 102))); // NOI18N tbProjetos.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); tbProjetos.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { tbProjetosMouseClicked(evt); } }); jScrollPane4.setViewportView(tbProjetos); txtPesquisaProjetos.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { txtPesquisaProjetosKeyReleased(evt); } }); jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/edu/ifnmg/alvespereira/segurancadados/icones/7181_16x16.png"))); // NOI18N jLabel3.setText("Nome do Projeto:"); javax.swing.GroupLayout jPanelBuscaLayout = new javax.swing.GroupLayout(jPanelBusca); jPanelBusca.setLayout(jPanelBuscaLayout); jPanelBuscaLayout.setHorizontalGroup( jPanelBuscaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelBuscaLayout.createSequentialGroup() .addContainerGap() .addGroup(jPanelBuscaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelBuscaLayout.createSequentialGroup() .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 547, Short.MAX_VALUE) .addContainerGap()) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelBuscaLayout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addGroup(jPanelBuscaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3) .addGroup(jPanelBuscaLayout.createSequentialGroup() .addComponent(txtPesquisaProjetos, javax.swing.GroupLayout.PREFERRED_SIZE, 353, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel2))) .addGap(136, 136, 136)))) ); jPanelBuscaLayout.setVerticalGroup( jPanelBuscaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelBuscaLayout.createSequentialGroup() .addGap(17, 17, 17) .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanelBuscaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txtPesquisaProjetos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2)) .addGap(18, 18, 18) .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); jPanelBuscaLayout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {jLabel2, txtPesquisaProjetos}); jPanelDadosProjetos.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Dados do Projeto", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 12), new java.awt.Color(0, 102, 102))); // NOI18N lblNome.setText("Nome:"); lblDescricao.setText("Descrição:"); txtDescricaoProjeto.setColumns(20); txtDescricaoProjeto.setRows(5); txtDescricao.setViewportView(txtDescricaoProjeto); lblDataInicio.setText("Data Início:"); lblDataTermino.setText("Data Término:"); cbDepartamentos.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N cbDepartamentos.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); cbDepartamentos.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cbDepartamentosActionPerformed(evt); } }); cbDepartamentos.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { cbDepartamentosFocusGained(evt); } }); lblDepartamento.setText("Departamento:"); btnSalvarAlteracao.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/edu/ifnmg/alvespereira/segurancadados/icones/filesave-icone-8124-32.png"))); // NOI18N btnSalvarAlteracao.setText("Salvar Alterações"); btnSalvarAlteracao.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSalvarAlteracaoActionPerformed(evt); } }); btnExcluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/edu/ifnmg/alvespereira/segurancadados/icones/8443_32x32.png"))); // NOI18N btnExcluir.setText("Excluir"); btnExcluir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnExcluirActionPerformed(evt); } }); jLabel1.setText("Cod:"); txtCod.setEditable(false); txtCod.setBackground(new java.awt.Color(204, 204, 204)); txtCod.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N txtCod.setForeground(new java.awt.Color(0, 102, 102)); try { txtDataInicio.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####"))); } catch (java.text.ParseException ex) { ex.printStackTrace(); } try { txtDataTermino.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####"))); } catch (java.text.ParseException ex) { ex.printStackTrace(); } javax.swing.GroupLayout jPanelDadosProjetosLayout = new javax.swing.GroupLayout(jPanelDadosProjetos); jPanelDadosProjetos.setLayout(jPanelDadosProjetosLayout); jPanelDadosProjetosLayout.setHorizontalGroup( jPanelDadosProjetosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelDadosProjetosLayout.createSequentialGroup() .addGap(155, 155, 155) .addComponent(btnSalvarAlteracao) .addGap(34, 34, 34) .addComponent(btnExcluir) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelDadosProjetosLayout.createSequentialGroup() .addContainerGap(21, Short.MAX_VALUE) .addGroup(jPanelDadosProjetosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelDadosProjetosLayout.createSequentialGroup() .addGroup(jPanelDadosProjetosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblDescricao, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanelDadosProjetosLayout.createSequentialGroup() .addGroup(jPanelDadosProjetosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblDepartamento, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lblDataInicio)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanelDadosProjetosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(cbDepartamentos, javax.swing.GroupLayout.PREFERRED_SIZE, 314, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelDadosProjetosLayout.createSequentialGroup() .addGap(4, 4, 4) .addComponent(txtDataInicio) .addGap(18, 18, 18) .addComponent(lblDataTermino) .addGap(18, 18, 18) .addComponent(txtDataTermino, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE))))) .addGap(137, 137, 137)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelDadosProjetosLayout.createSequentialGroup() .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(txtCod, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(lblNome) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(txtNomeProjeto, javax.swing.GroupLayout.PREFERRED_SIZE, 387, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelDadosProjetosLayout.createSequentialGroup() .addComponent(txtDescricao, javax.swing.GroupLayout.PREFERRED_SIZE, 536, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()))) ); jPanelDadosProjetosLayout.setVerticalGroup( jPanelDadosProjetosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelDadosProjetosLayout.createSequentialGroup() .addGap(20, 20, 20) .addGroup(jPanelDadosProjetosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblNome) .addComponent(txtNomeProjeto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtCod, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(lblDescricao, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtDescricao, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanelDadosProjetosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblDataInicio) .addComponent(lblDataTermino) .addComponent(txtDataInicio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtDataTermino, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanelDadosProjetosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(cbDepartamentos, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE) .addComponent(lblDepartamento)) .addGap(18, 18, 18) .addGroup(jPanelDadosProjetosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnSalvarAlteracao) .addComponent(btnExcluir)) .addContainerGap()) ); btnOK.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/edu/ifnmg/alvespereira/segurancadados/icones/bullet-aller-icone-7275-32.png"))); // NOI18N btnOK.setText("Ok"); btnOK.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnOKActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanelDadosProjetos, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanelBusca, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btnOK, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(38, 38, 38)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(17, 17, 17) .addComponent(jPanelBusca, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(19, 19, 19) .addComponent(jPanelDadosProjetos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(btnOK, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents
8620d951-3aa5-438e-9a8a-cec6be08815c
7
public void stateChanged(ChangeEvent e) { if (model.getLightSource() == null) return; Object o = e.getSource(); if (o instanceof JSlider) { JSlider source = (JSlider) o; if (!source.getValueIsAdjusting()) { model.setLightSourceInterval((int) ((200 + (source.getMaximum() - source.getValue()) * 20) / model .getTimeStep())); model.notifyChange(); } } else if (o instanceof JSpinner) { JSpinner source = (JSpinner) o; Object v = source.getValue(); if (v instanceof Number) { int i = (int) ((Number) v).doubleValue(); SpinnerModel spinnerModel = source.getModel(); if (spinnerModel instanceof SpinnerNumberModel) { Comparable c = ((SpinnerNumberModel) spinnerModel).getMaximum(); if (c instanceof Number) { double x = ((Number) c).doubleValue(); model.setLightSourceInterval((int) ((200 + (int) ((x + 1 - i) * 20)) / model.getTimeStep())); model.notifyChange(); } } } else { System.err.println("Incorrect spinner value"); } } }
1dd30560-f683-4481-b2ca-8bc9816eb459
6
public void dbData(int uName) { try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { System.out.println("Where is your MySQL JDBC Driver?"); e.printStackTrace(); } if (uName >= 0) { PreparedStatement ps = null; Connection con = null; ResultSet rs = null; try { con = DriverManager.getConnection("jdbc:mysql://mysql2.cs.stonybrook.edu:3306/mlavina", "mlavina", "108262940"); if (con != null) { con.setAutoCommit(false); try { String sql = "select id,ssn from employee where id = '" + uName + "'"; ps = con.prepareStatement(sql); rs = ps.executeQuery(); rs.next(); dbName = rs.getInt("id"); dbPassword = rs.getInt("ssn"); con.commit(); } catch (Exception e) { con.rollback(); } } } catch (SQLException sqle) { sqle.printStackTrace(); } finally { try { con.setAutoCommit(true); con.close(); ps.close(); } catch (Exception e) { e.printStackTrace(); } } } }
089cb618-5ecb-40dd-8ed8-5a479d9c379f
9
public String getConfigPath(String filename) { if (eng.isApplet()) return null; File jgamedir; try { jgamedir = new File(System.getProperty("user.home"), ".jgame"); } catch (Exception e) { // probably AccessControlException of unsigned webstart return null; } if (!jgamedir.exists()) { // try to create ".jgame" if (!jgamedir.mkdir()) { // fail return null; } } if (!jgamedir.isDirectory()) return null; File file = new File(jgamedir,filename); // try to create file if it didn't exist try { file.createNewFile(); } catch (IOException e) { return null; } if (!file.canRead()) return null; if (!file.canWrite()) return null; try { return file.getCanonicalPath(); } catch (IOException e) { return null; } }
e2833ab8-0d87-43d9-95ab-8df6c82c547c
7
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(ClientGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ClientGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ClientGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ClientGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> Registry registry; try { registry = LocateRegistry.getRegistry(1099); obj = (LoanServerInterface) registry.lookup("LoanServerInterface"); } catch (RemoteException | NotBoundException ex) { Logger.getLogger(ClientGUI.class.getName()).log(Level.SEVERE, null, ex); } /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new ClientGUI().setVisible(true); } }); }
a6fb2437-b2ba-4efb-b6e1-2b6419d9bbfb
9
private String[] splitString(String ipFormula) throws ScriptSyntaxException { LinkedList<String> tokens = new LinkedList<String>(); int braces=0;//level of braces //considering that there is always only one space int posBegin=0; int posEnd=0; while (posEnd<ipFormula.length()){ if (isSpace(ipFormula.charAt(posEnd)) && braces==0){ //space found String token=ipFormula.substring(posBegin,posEnd).trim(); if (token.length()!=0) tokens.add(token);//adding only non-empty tokens posBegin=posEnd;//moving to the next token } if (ipFormula.charAt(posEnd)=='(') braces++; if (ipFormula.charAt(posEnd)==')') braces--; posEnd++; } String token=ipFormula.substring(posBegin,posEnd).trim(); if (token.length()!=0) tokens.add(token);//adding only non-empty tokens //tokens parsed //checking braces consistency if (braces!=0){ throw new ScriptSyntaxException("Braces are inconsistent: "+ipFormula); } String[] rval=new String[tokens.size()]; int i=0; for (Iterator<String> iToken = tokens.iterator(); iToken.hasNext();++i) { rval[i] = iToken.next(); } //returning array. temporary list is thrown away. return rval; }
b740c121-b4ae-4348-b04e-fd503e84d754
3
public static FlacMetadataBlock create(InputStream inp) throws IOException { int typeI = inp.read(); if(typeI == -1) { throw new IllegalArgumentException(); } byte type = IOUtils.fromInt(typeI); byte[] l = new byte[3]; IOUtils.readFully(inp, l); int length = (int)IOUtils.getInt3BE(l); byte[] data = new byte[length]; IOUtils.readFully(inp, data); switch(type) { case STREAMINFO: return new FlacInfo(data, 0); case VORBIS_COMMENT: return new FlacTags.FlacTagsAsMetadata(data); default: return new FlacUnhandledMetadataBlock(type, data); } }
5008e4b2-a3bd-4636-9dcb-a7b5ebad7a5d
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(LoaderXML.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(LoaderXML.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(LoaderXML.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(LoaderXML.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 LoaderXML().setVisible(true); } }); }
6ba28740-7ee6-4d2d-bda6-6eb2b73e9463
1
public final JSONObject optJSONObject(int index) { Object o = opt(index); return o instanceof JSONObject ? (JSONObject)o : null; }
02d0d22c-7482-4dc5-b69e-abeb57597eac
2
private boolean first_round_strategy() { if (bowlId < chooseLimit) { maxScoreSoFar = Math.max( maxScoreSoFar, get_bowl_score(bowl) ); System.out.println("Not reached chooseLimit yet, updated maxScoreSoFar = " + maxScoreSoFar); return false; } else { if (get_bowl_score(bowl) >= maxScoreSoFar) { System.out.println("Score = " + get_bowl_score(bowl) + " better than maxScoreSoFar = " + maxScoreSoFar + ", choose it!"); return true; } } System.out.println(get_bowl_score(bowl) + "is worse than maxScoreSoFar " + maxScoreSoFar + " , pass it"); return false; }
de1870db-b651-4ca4-97e1-edd1f9a0ce29
0
@Override public int eatNumber() { return 0; }
d328919e-31af-43e4-9652-a0db056072bd
0
public Game() { Level level = new SpawnLevel(this); currentScreen = new GameScreen(this, level); mouse = new Mouse(this); addMouseListener(mouse); keyboard = new Keyboard(this); addKeyListener(keyboard); player = new Player(level, 30, 100); }
85297320-a14b-4d0a-b67f-d90b033b4d00
2
public double visibleBias(int index) { if(index < 0 || index >= m) throw new RuntimeException("given m=" + m + ", illegal value for index: " + index); return _visibleBias[index]; }
1149f6d0-1e40-48cb-a0ed-de63733a1aa6
2
@Override public int compareTo(Entity o) { if (id > o.id) { return 1; } if (id < o.id) { return -1; } return 0; }
26500a8d-642e-4833-b9fb-2c6f30ec5754
1
@Transactional public Journal getOrCreateJournal(String name, Date date) { Journal journal = journalsDao.getByName(name); if (journal != null) { Date startDate = dateService.getStartOfDay(date); Date endDate = dateService.getNextDay(date); journal.setTasks(tasksDao.getActiveForPeriod(journal, startDate, endDate)); return journal; } return createJournal(name); }
38c36820-43ff-40f5-a806-3d696d40c0e1
9
private void refreshStatistics(ArrayList<T[]> gens) { double max, min, avg, current; avg = max = min = problem.costFunction(gens.get(0)); for (int i = 1; i < gens.size(); ++i) { current = problem.costFunction(gens.get(i)); if (max < current) { max = current; if (problem.isGreaterCostBetter() && (bestSolution == null || max > problem.costFunction(bestSolution))) { bestSolution = gens.get(i); bestSolutionCost=current; } } if(min>current){ min = current; if (!problem.isGreaterCostBetter() && (bestSolution == null || min < problem.costFunction(bestSolution))) { bestSolution = gens.get(i); bestSolutionCost=current; } } avg += current; } avg /= gens.size(); this.max.add(max); this.avg.add(avg); this.min.add(min); }
d0a58fba-483a-4ec8-ac6b-af8199e19543
3
@Override public void draw(Graphics g) { g.setColor(Color.WHITE); g.setFont(new Font("Tahoma", Font.PLAIN, FONT_SIZE - FONT_SIZE/4)); switch (type) { case 0: g.drawString("T", x, y); break; case 1: g.drawString("+", x, y); break; case 2: g.drawString("-", x, y); break; } g.setFont(new Font(g.getFont().getFontName(), g.getFont().getStyle(), g.getFont().getSize() - 2)); }
36efd515-bbcf-41ae-8ea4-d2314af0a2a3
5
private int indOfOutP( char op, String equ ){ int PDepth = 0; for (int i = 0; i < equ.length(); i++){ if (equ.charAt(i) == '(') PDepth++; else if (equ.charAt(i) == ')') PDepth--; else if (PDepth == 0){ if (equ.charAt(i) == op) return i; } } return -1; }
e85e8c0a-e180-4b8d-9827-e420eeecdb16
8
public String typeConveter(byte val) { String rString = "?"; switch(val) { case STRING: rString = "String"; break; case HIT_TEST: rString = "Hit Test"; break; case SHIP: rString = "Ship"; break; case SHIPKILLED: rString = "Ship Killed"; break; case SHIPALIVE: rString = "Ship Alive"; break; case ROCKSRequest: rString = "Rocks Request"; break; case ROCKSResponse: rString = "Rocks Response"; break; case ROCKHIT: rString = "Rocks Hit"; break; } return rString; }
bd5357b3-bef1-41b5-a770-08d21f87f15c
8
protected static int getNPrime(int n) { if (n == 1) return FIRST_PRIME; if (n == 2) return SECOND_PRIME; int prime = SECOND_PRIME; int count = 2; for (int i : primesByOrder.keySet()) { if (n > i) { count = i; prime = primesByOrder.get(i); } else break; } while (count < n) { prime += ADVANCE; boolean isPrime = true; for (int i = FIRST_PRIME; i * i <= prime; i++) { if (prime % i == 0) { isPrime = false; break; } } if (isPrime) count++; } return prime; }
90cb1b56-9793-4c0b-b04c-79d86172cc6b
0
public int getNewPosition() { return this.newPosition; }
33be7ce0-d846-487c-8d18-9b31cbd85b5e
3
public Evaluator(String expression){ Stack<Expression> expressionStack = new Stack<Expression>(); for (String token : expression.split(" ")){ if (token.equals("+")) { Expression subExpression = new Plus(expressionStack.pop(), expressionStack.pop()); expressionStack.push(subExpression); } else if (token.equals("-")){ Expression left = expressionStack.pop(); Expression right = expressionStack.pop(); Expression subExpression = new Minus(left, right); expressionStack.push(subExpression); } else expressionStack.push(new Variable(token)); } syntaxTree = expressionStack.pop(); }
5e2a6383-c14d-45cf-890c-13793bc55015
4
private String serverRecievedSendFrame(SendFrame msg){ String reply= ""; if (msg.getMessage().equals("stats\n")) Statistics.getStatisticsObject().getStats(); else if (msg.getMessage().equals("stop\n")) _cH.stopServer(); else if (msg.getMessage().equals("clients online\n")) reply= _users.getListOfAllUsers(true); else if (msg.getMessage().equals("clients\n")) reply= _users.getListOfAllUsers(false); return reply; }
c2c12b24-bd4f-48ea-990c-0231c924a31d
4
protected boolean canEnter(Tile t) { if (t == init || t == destination) return true ; return t.habitat().pathClear && ( t.owner() == null || t.owner().owningType() < priority ) ; }