text
stringlengths
14
410k
label
int32
0
9
@Override public Object getValue() { Object o = null; ; Formula f = (Formula) getParentRec(); if( f.isSharedFormula() ) { o = FormulaCalculator.calculateFormula( f.shared.instantiate( f ) ); // throw new UnsupportedOperationException ( // "Shared formulas must be instantiated for calculation"); } else { Object r = null; if( f.getInternalRecords().size() > 0 ) { r = f.getInternalRecords().get( 0 ); } else { // it's part of an array formula but not the parent r = getParentRec().getSheet().getArrayFormula( getReferent() ); } if( r instanceof Array ) { Array arr = (Array) r; o = arr.getValue( this ); } else if( r instanceof StringRec ) { o = ((StringRec) r).getStringVal(); } } return o; }
4
protected File getFile(final String key) { return getProperty(key) == null ? null : new File(working_directory, getProperty(key)); }
1
private String getMeleeTier(ItemDefinition definition) { if (definition.wieldRequirements().size() >= 3) { return "HIGH_LEVEL"; } for (CombatSkillRequirement requirement : definition.wieldRequirements()) { if (requirement.getLevel() <= 45) { return "LOW_LEVEL"; } else if (requirement.getLevel() < 70) { return "MID_LEVEL"; } else { return "HIGH_LEVEL"; } } return "LOW_LEVEL"; }
4
public int maxProfit(int[] prices) { int[] A = prices; if (A.length < 2) return 0; int buy = 0; int sell = 1; int max = Math.max(A[sell] - A[buy], 0); while (sell < A.length) { max = Math.max(A[sell] - A[buy], max); if (A[sell] < A[buy]) buy = sell; sell++; } return max; }
3
private JSONWriter append(String string) throws JSONException { if (string == null) { throw new JSONException("Null pointer"); } if (this.mode == 'o' || this.mode == 'a') { try { if (this.comma && this.mode == 'a') { this.writer.write(','); } this.writer.write(string); } catch (IOException e) { throw new JSONException(e); } if (this.mode == 'o') { this.mode = 'k'; } this.comma = true; return this; } throw new JSONException("Value out of sequence."); }
7
public static void main(String args[]) { long begin=System.currentTimeMillis(); GetOutAuthorRelation getOutAuthorRelation = new GetOutAuthorRelation(); HashMap<String, Map<String, Integer>> map = getOutAuthorRelation .GetOutRelation(4); //86603 for (String key : map.keySet()) { Map<String, Integer> tmpMap = map.get(key); System.out.print(key + "\t"); for (String obj : tmpMap.keySet()) { System.out.print(obj + "-" + tmpMap.get(obj) + "\t"); } System.out.println(); } long end=System.currentTimeMillis(); System.out.println("total time: "+(end-begin)/1000); }
2
public void process(Object selectKey){ if(selectKey instanceof SelectionKey){ SelectionKey selectionKey = (SelectionKey)selectKey; Client key = Client.getSockector(selectionKey); if(key.getMessages(charBuffer)){ // 已完成握手,从客户端读取报刊 key.process();// 进行业务处理 } }else if(selectKey instanceof Client){// 直接发送消息 ((Client)selectKey).send(); } }
3
private void checkBlockMult( int operationType , boolean transA , boolean transB , Method method, final int heightA, final int widthA, final int widthB ) { boolean hasAlpha = method.getParameterTypes().length == 10; if( hasAlpha && operationType == -1 ) fail("No point to minus and alpha"); DenseMatrix64F A = RandomMatrices.createRandom(heightA,widthA,rand); DenseMatrix64F B = RandomMatrices.createRandom(widthA,widthB,rand); DenseMatrix64F C = new DenseMatrix64F(heightA,widthB); if( operationType == -1 ) CommonOps.mult(-1,A,B,C); else CommonOps.mult(A,B,C); DenseMatrix64F C_found = new DenseMatrix64F(heightA,widthB); // if it is set then it should overwrite everything just fine if( operationType == 0) RandomMatrices.setRandom(C_found,rand); if( transA ) CommonOps.transpose(A); if( transB ) CommonOps.transpose(B); double alpha = 2.0; if( hasAlpha ) { CommonOps.scale(alpha,C); } invoke(method,alpha,A.data,B.data,C_found.data,0,0,0,A.numRows,A.numCols,C_found.numCols); if( !MatrixFeatures.isIdentical(C,C_found,1e-10) ) { C.print(); C_found.print(); System.out.println("Method "+method.getName()); System.out.println("transA " +transA); System.out.println("transB " +transB); System.out.println("type " +operationType); System.out.println("alpha " +hasAlpha); fail("Not identical"); } }
8
public static void main(String[] args) { int hashSize = 0; if (args.length == 0) { throw new IllegalArgumentException("Syntax: CountsWords Datei [hashSize][RSHash|JSHash]"); } if (args.length >= 1) file = args[0]; if (args.length >= 2) { try { hashSize = Integer.parseInt(args[1]); } catch (NumberFormatException ex) { hashMethod = args[1]; hashSize = 10; } } if ( args.length == 3 ) hashMethod = args[2]; if ( hashMethod.equals("") ) hashMethod = "RSHash"; if (hashSize > 0) hashTable = new HashTable(hashSize, hashMethod); else throw new NumberFormatException("Die Hashsize muss größer als 0 sein !"); try { hashTable = readFileAndHash(file, hashSize, hashMethod); if(hashTable != null){ printStatistics(hashTable); } System.out.println("Anzahl der Kollisionen: " + hashTable.numberOfCollisions()); } catch (Exception e) { System.out.println("Syntax: CountsWords Datei [hashSize][RSHash|JSHash]"); } }
9
private final static ArrayList<String> getRowColAndGapsTrimmed(String s) { if (s.indexOf('|') != -1) s = s.replaceAll("\\|", "]["); ArrayList<String> retList = new ArrayList<String>(Math.max(s.length() >> 2 + 1, 3)); // Aprox return length. int s0 = 0, s1 = 0; // '[' and ']' count. int st = 0; // Start of "next token to add". for (int i = 0, iSz = s.length(); i < iSz; i++) { char c = s.charAt(i); if (c == '[') { s0++; } else if (c == ']') { s1++; } else { continue; } if (s0 != s1 && (s0 - 1) != s1) break; // Wrong [ or ] found. Break for throw. retList.add(s.substring(st, i).trim()); st = i + 1; } if (s0 != s1) throw new IllegalArgumentException("'[' and ']' mismatch in row/column format string: " + s); if (s0 == 0) { retList.add(""); retList.add(s); retList.add(""); } else if (retList.size() % 2 == 0) { retList.add(s.substring(st, s.length())); } return retList; }
9
private void btnAlterarProdutoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAlterarProdutoActionPerformed try { if (JOptionPane.showConfirmDialog(rootPane, "Deseja Salvar?") == 0) { carregaObjeto(); if (dao.Salvar(produto)) { JOptionPane.showMessageDialog(rootPane, "Salvo com sucesso!"); //Chamar NOVAMENTE a janela de listagem de Produtos frmProdutoListar janela = new frmProdutoListar(); this.getParent().add(janela); janela.setVisible(true); this.setVisible(false); } else { JOptionPane.showMessageDialog(rootPane, "Falha ao salvar! Consulte o administrador do sistema!"); } } else { JOptionPane.showMessageDialog(rootPane, "Operação cancelada!"); } } catch (Exception ex) { JOptionPane.showMessageDialog(rootPane, "Erro ao salvar! Consulte o administrador do sistema!"); } }//GEN-LAST:event_btnAlterarProdutoActionPerformed
3
private void doEditCY(HttpServletRequest request, HttpServletResponse response, boolean isEditUser) throws ServletException, IOException { String chengYuanId = StringUtil.toString(request.getParameter("chengYuanId")); if(!StringUtil.isEmpty(chengYuanId)) { ChengYuan chengYuan = null; try { chengYuan = manager.findCYById(chengYuanId); if(chengYuan != null) { request.setAttribute("isEdit",isEditUser); request.setAttribute("currentCYObj",chengYuan); request.getRequestDispatcher("/admin/tuandui/editChengYuan.jsp").forward(request,response); return; } } catch (SQLException e) { logger.error("查看成员失败",e); request.setAttribute("errorMsg","查看成员失败"); request.getRequestDispatcher("/admin/error.jsp").forward(request,response); return; } } }
3
public SpriteHuntArgs(Map<String, String> argMap) { boolean _hasErrors = false; String huntColor = "255,0,255"; if (argMap.containsKey("hunt")) { huntColor = argMap.get("hunt"); } Integer parsedHuntColor = parseHuntColor(huntColor); if (parsedHuntColor == null) { _hasErrors = true; System.err.println(" hunt specified by --hunt makes no sense '" + huntColor + "'"); this.hunt = 0; } else { this.hunt = parsedHuntColor.intValue(); } String input = argMap.get("input"); if (input == null) { System.err.println(" --input file must be specified"); this.inputFile = null; this.format = null; _hasErrors = true; } else { this.inputFile = new File(input); this.format = Common.getFormat(input); if (!inputFile.exists()) { System.err.println(" --input file must exist"); _hasErrors = true; } if (!inputFile.isFile()) { System.err.println(" --input file must be a file"); _hasErrors = true; } } String output = argMap.get("output"); if (output == null) { System.err.println(" --output directory must be specified"); this.outputPath = null; _hasErrors = true; } else { this.outputPath = new File(output); if (!outputPath.exists()) { System.err.println(" --output file must exist"); _hasErrors = true; } if (!outputPath.isDirectory()) { System.err.println(" --output file must be a directory"); _hasErrors = true; } } String prefix = "extracted"; if (argMap.containsKey("prefix")) { prefix = argMap.get("prefix"); } this.prefix = prefix; this.hasErrors = _hasErrors; }
9
@Override public Event next() { String input = null; try { input = br.readLine(); } catch (IOException e) { e.printStackTrace(); } //alters state if(input == null || input.equals("")){ return new DefaultState(as); } if(input.equalsIgnoreCase("add")){ return new AuctionCreateState(name, as); } else{ return new SearchResultsState(as, name, input); } }
4
public Category decide(Game game) { if (game.getWhichRoll() == 3 || rnd.nextInt(4) == 0) { // Score the dice. int numAvailable = 0; int chosenColumn = -1; Category chosenCategory = null; for (int column = 0; column < 3; column++) { ScoreColumn scoreColumn = game.getCurrentPlayer().getScoreColumn(column); for (Category category : Category.allCategories) { if (scoreColumn.getScore(category) == null) { // not selected yet, so consider it numAvailable++; if (chosenCategory == null || rnd.nextInt(numAvailable) == 0) { chosenColumn = column; chosenCategory = category; } } } } game.setScore(chosenColumn, chosenCategory); return chosenCategory; } else { // Randomly select dice to re-roll for (int die = 0; die < Dice.numDice; die++) { game.getDice().setSelected(die, rnd.nextBoolean()); } return null; } }
8
@Override public int compareTo(Object other) { if (other instanceof Vortex) { Vortex otherVortex = (Vortex)other; if (otherVortex.dayDistance > this.dayDistance) { return 1; } else if (otherVortex.dayDistance < this.dayDistance) { return -1; } else { if (otherVortex.dayTravel > this.dayTravel) { return 1; } else if (otherVortex.dayTravel < this.dayTravel) { return -1; } else { return 0; } } } return -1; }
5
public int getWinner() { int player1Score = getScore(1); int player2Score = getScore(2); if (player1Score > player2Score) return 1; if (player2Score > player1Score) return 2; else return 3; }
2
private int processJsrRanges() { List<JsrRecord> lstJsrAll = new ArrayList<>(); // get all jsr ranges for (Entry<BasicBlock, BasicBlock> ent : subroutines.entrySet()) { BasicBlock jsr = ent.getKey(); BasicBlock ret = ent.getValue(); lstJsrAll.add(new JsrRecord(jsr, getJsrRange(jsr, ret), ret)); } // sort ranges // FIXME: better sort order List<JsrRecord> lstJsr = new ArrayList<>(); for (JsrRecord arr : lstJsrAll) { int i = 0; for (; i < lstJsr.size(); i++) { JsrRecord arrJsr = lstJsr.get(i); if (arrJsr.range.contains(arr.jsr)) { break; } } lstJsr.add(i, arr); } // find the first intersection for (int i = 0; i < lstJsr.size(); i++) { JsrRecord arr = lstJsr.get(i); Set<BasicBlock> set = arr.range; for (int j = i + 1; j < lstJsr.size(); j++) { JsrRecord arr1 = lstJsr.get(j); Set<BasicBlock> set1 = arr1.range; if (!set.contains(arr1.jsr) && !set1.contains(arr.jsr)) { // rang 0 doesn't contain entry 1 and vice versa Set<BasicBlock> setc = new HashSet<>(set); setc.retainAll(set1); if (!setc.isEmpty()) { splitJsrRange(arr.jsr, arr.ret, setc); return 1; } } } } return 0; }
9
public Game.PlayerTurn getPlayerTurn() { boolean test = false; if (test || m_test) { System.out.println("Game :: getPlayerTurn() BEGIN"); } if (test || m_test) { System.out.println("Game :: getPlayerTurn() END"); } return m_playerTurn; }
4
public Tree additiveExpressionPro(){ Tree firstConditionalExpression = null, secondConditionalExpression = null; if((firstConditionalExpression = multiplicativeExpressionPro()) != null){ if((secondConditionalExpression = additiveExpressionDashPro(firstConditionalExpression)) != null){ return secondConditionalExpression; } return firstConditionalExpression; } return null; }
2
private int arrayState( char next ) { if ( next == ',' ) { buffer.pop(); next = nextValue(); } switch (next) { case END_ARRAY: { popState(); return returnValue( END_ARRAY, state ); } case '"': { parseAndSetString(); return returnValue( STRING, state ); } case START_OBJECT: { pushAndSetState( STATE_OBJECT ); return returnValue( START_OBJECT, state ); } case START_ARRAY: { pushAndSetState( STATE_ARRAY ); return returnValue( START_ARRAY, state ); } default: { return defaultArrayState( next ); } } }
5
public void setCity(String city) { this.city = city; }
0
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof KeyWrapper)) return false; KeyWrapper other = (KeyWrapper) obj; if (cacheName == null) { if (other.cacheName != null) return false; } else if (!cacheName.equals(other.cacheName)) return false; if (key == null) { if (other.key != null) return false; } else if (!key.equals(other.key)) return false; return true; }
9
private void initGenes(){ //0 to n-1 for the cities, n to denote the seperator. Superfluous numbers are being ignored bitsPerAllele = (int) (Math.log(travelingSalesman.n)/Math.log(2)); //2n alleles, as we use pair permutations allelesCount = 2*travelingSalesman.n; bitsPerGene = (allelesCount*bitsPerAllele); bytesPerGene = (bitsPerGene+Byte.SIZE-1)/Byte.SIZE; genes = new Gene[POPULATION_SIZE]; oldGenes = new Gene[POPULATION_SIZE]; //random initial genes for(int i = 0;i<genes.length;i++){ byte[] geneData = new byte[bytesPerGene]; Environment.random.nextBytes(geneData); genes[i] = new Gene(geneData, this); oldGenes[i] = new Gene(new byte[bytesPerGene], this); } }
1
public String[] someoneElse(boolean place) { try{ driver.get(baseUrl + "/content/lto/2013.html"); //global landing page driver.findElement(By.xpath("/html/body/div[2]/div/div/div/div/div/div/div[2]/ul/li/a")).click(); //Austrailia landing page - Order Now button driver.findElement(By.xpath("/html/body/div[3]/div/div/div/div[3]/div/div[3]/div/div/a")).click(); //buyer select radio button driver.findElement(By.xpath("/html/body/div[2]/div/div/div/div/form/div/div[2]/div/span")).click(); //buyer select continue button driver.findElement(By.xpath("/html/body/div[2]/div/div/div/div/form/div/div[3]/div/div/div/p")).click(); //buyer page info driver.findElement(By.id("distributorID")).clear(); driver.findElement(By.id("distributorID")).sendKeys("US8128558"); driver.findElement(By.id("email")).clear(); driver.findElement(By.id("email")).sendKeys("test@test.com"); //driver.findElement(By.cssSelector("a.selector")).click(); //driver.findElement(By.xpath("/html/body/div[2]/div/div/div/div/div/div/div/form/div/div[2]/div/div[3]/div/div[2]/div/div/div/ul/li[2]")).click(); driver.findElement(By.id("user_phone_2")).clear(); driver.findElement(By.id("user_phone_2")).sendKeys("456"); driver.findElement(By.id("user_phone_3")).clear(); driver.findElement(By.id("user_phone_3")).sendKeys("456"); driver.findElement(By.id("buyerID")).clear(); driver.findElement(By.id("buyerID")).sendKeys("US8128558"); driver.findElement(By.id("buyerPhone_2")).clear(); driver.findElement(By.id("buyerPhone_2")).sendKeys("456"); driver.findElement(By.id("buyerPhone_3")).clear(); driver.findElement(By.id("buyerPhone_3")).sendKeys("4565"); driver.findElement(By.id("nameOfPerson")).clear(); driver.findElement(By.id("nameOfPerson")).sendKeys("Test User"); driver.findElement(By.id("address_address1")).clear(); driver.findElement(By.id("address_address1")).sendKeys("75 West Center Street"); driver.findElement(By.id("address_address2")).clear(); driver.findElement(By.id("address_address2")).sendKeys("Test Address"); driver.findElement(By.id("address_postalCode")).clear(); driver.findElement(By.id("address_postalCode")).sendKeys("BM1326"); driver.findElement(By.xpath("/html/body/div[2]/div/div/div[2]/div/div/div/p/a")).click(); //Buyer validation page driver.findElement(By.xpath("/html/body/div[2]/div/div/div/div/div/div/div/div/div/form/div/div/div/a")).click(); //product page driver.findElement(By.id("checkout")).click(); if (isElementPresent(By.className("shopError"))) { results[0] = "Austrailia: Failed: Someone Else\n"+ "URL: " + driver.getCurrentUrl() + "\n" + "Error: " + driver.findElement(By.className("shopError")).getText(); return results; } //shop app try{ Thread.sleep(100); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } driver.findElement(By.cssSelector("option[value=\"addPaymentType0\"]")).click(); driver.findElement(By.id("paymentNumber_id")).clear(); driver.findElement(By.id("paymentNumber_id")).sendKeys("4111111111111111"); driver.findElement(By.id("paymentName_id")).clear(); driver.findElement(By.id("paymentName_id")).sendKeys("bob"); driver.findElement(By.id("paymentSecurityNumber")).clear(); driver.findElement(By.id("paymentSecurityNumber")).sendKeys("456"); driver.findElement(By.xpath("/html/body/form/div/div[7]/div/div[5]/div/div/div/div[6]/div[3]/div[2]/button")).click(); try{ Thread.sleep(5000); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } if (place) { driver.findElement(By.xpath("/html/body/form/div/div[12]/div/button")).click(); if (isElementPresent(By.className("shopError"))) { results[0] = "Austrailia: Failed: Someone Else After Shop\n"+ "URL: " + driver.getCurrentUrl() + "\n" + "Error: " + driver.findElement(By.className("shopError")).getText(); return results; } if (!isElementPresent(By.id("productinformation-complete"))) { results[0] = "Austrailia: Failed: Order was not completed"; return results; } results[2] = driver.findElement(By.xpath("/html/body/form/div/div[2]/h2")).getText(); } results[0] = "Austrailia: Passed"; return results; } catch (Exception e) { results[0] = "Austrailia: Someone Else\n"+ "URL: " + driver.getCurrentUrl() + "\n" + "Script Error: " + e; return results; } }
7
@Override public Object read(JsonReader in) throws IOException { JsonToken token = in.peek(); switch (token) { case BEGIN_ARRAY: List<Object> list = new ArrayList<Object>(); in.beginArray(); while (in.hasNext()) { list.add(read(in)); } in.endArray(); return list; case BEGIN_OBJECT: Map<String, Object> map = new LinkedTreeMap<String, Object>(); in.beginObject(); while (in.hasNext()) { map.put(in.nextName(), read(in)); } in.endObject(); return map; case STRING: return in.nextString(); case NUMBER: return in.nextDouble(); case BOOLEAN: return in.nextBoolean(); case NULL: in.nextNull(); return null; default: throw new IllegalStateException(); } }
8
public void changeTable(String inFname, String outFname) throws IOException{ TextFile in = new TextFile(inFname, false); TextFile out = new TextFile(outFname, true); String[] els = in.readLineElems(TextFile.tab); getPosToSampleId(els); out.writelnTabDelimited(els); String gene; float rpkm; int len; while ( (els = in.readLineElems(TextFile.tab)) != null ){ gene = els[0]; len = geneLengths.get(gene); out.write(gene); for (int i = 1; i < els.length; i++){ rpkm = (1000000000*Float.parseFloat(els[i]))/(numMapped.get(posToSampleId.get(i))*(long)len); out.write("\t" + rpkm); } out.writeln(); } in.close(); out.close(); }
2
public void testSetHourOfDay_int2() { MutableDateTime test = new MutableDateTime(2002, 6, 9, 5, 6, 7, 8); try { test.setHourOfDay(24); fail(); } catch (IllegalArgumentException ex) {} assertEquals("2002-06-09T05:06:07.008+01:00", test.toString()); }
1
@Override public void draw(Graphics2D g) { super.draw(g); g.drawString(""+Loading.index , 10, 10); //inventory space g.drawImage(img.getSubimage(0, 63, 200, 18), 150, GamePanel.HEIGHT - 25, null); for(int slot = 0; slot < player.getMaxSlots(); slot++){ ItemStack stack = player.getStackInSlot(slot); if(stack != null) stack.getItem().draw(g, 165+ (17*slot), (GamePanel.HEIGHT - 24), stack); } }
2
private void testDescendingOrder(int numRows, int numCols, boolean compact, boolean testArray ) { SimpleMatrix U,W,V; int minLength = Math.min(numRows,numCols); double singularValues[] = new double[minLength]; if( compact ) { U = SimpleMatrix.wrap(RandomMatrices.createOrthogonal(numRows,minLength,rand)); W = SimpleMatrix.wrap(RandomMatrices.createDiagonal(minLength,minLength,0,1,rand)); V = SimpleMatrix.wrap(RandomMatrices.createOrthogonal(numCols,minLength,rand)); } else { U = SimpleMatrix.wrap(RandomMatrices.createOrthogonal(numRows,numRows,rand)); W = SimpleMatrix.wrap(RandomMatrices.createDiagonal(numRows,numCols,0,1,rand)); V = SimpleMatrix.wrap(RandomMatrices.createOrthogonal(numCols,numCols,rand)); } // Compute A SimpleMatrix A=U.mult(W).mult(V.transpose()); // extract array of singular values for( int i = 0; i < singularValues.length; i++ ) singularValues[i] = W.get(i,i); // put into descending order if( testArray ) { SingularOps.descendingOrder(U.getMatrix(),false,singularValues,minLength,V.getMatrix(),false); // put back into W for( int i = 0; i < singularValues.length; i++ ) W.set(i,i,singularValues[i]); } else { SingularOps.descendingOrder(U.getMatrix(),false,W.getMatrix(),V.getMatrix(),false); } // see if it changed the results SimpleMatrix A_found = U.mult(W).mult(V.transpose()); assertTrue(A.isIdentical(A_found,1e-8)); // make sure singular values are descending if( testArray ) { for( int i = 1; i < minLength; i++ ) { assertTrue(singularValues[i-1] >= singularValues[i]); } } else { for( int i = 1; i < minLength; i++ ) { assertTrue(W.get(i-1,i-1) >= W.get(i,i)); } } }
7
public void run() { if(url != null) { // Obtain the results of the project's file feed if(readFeed()) { if(versionCheck(versionTitle)) { String fileLink = getFile(versionLink); if(fileLink != null && type != UpdateType.NO_DOWNLOAD) { String name = file.getName(); // If it's a zip file, it shouldn't be downloaded as the plugin's name if(fileLink.endsWith(".zip")) { String [] split = fileLink.split("/"); name = split[split.length-1]; } saveFile(new File("plugins/" + updateFolder), name, fileLink); } else { result = UpdateResult.UPDATE_AVAILABLE; } } } } }
6
public void SetMean(double mean) { super.mean = mean; }
0
public Preferences(File prefsFile) { mFile = prefsFile; mPrefs = new Properties(); mNotifier = new Notifier(); if (mFile.exists()) { try (InputStream in = new FileInputStream(mFile)) { mPrefs.loadFromXML(in); } catch (Exception exception) { // Throw away anything we loaded, since the file must be corrupted. mPrefs = new Properties(); } } }
2
public ArrayList<String> tempResultQuery(ArrayList<String> temp, String query) { ArrayList<String> tempResults = new ArrayList<String>(); if (temp.isEmpty()) { docIdResults.clear(); docIdResultsBoolean.clear(); parser.clearStemmerFile(); ArrayList<String> p1 = new ArrayList<String>(); ArrayList<String> p2 = new ArrayList<String>(); String operator = ""; if (query.contains("&")) { operator = "&"; query = query.replaceAll("&", " "); stemQuery = parser.stemLine(query); String q1 = stemQuery.get(0); String q2 = stemQuery.get(1); p1 = searchWord(q1); p2 = searchWord(q2); } else if (query.contains("|")) { operator = "|"; query = query.replaceAll("\\|", " "); stemQuery = parser.stemLine(query); String q1 = stemQuery.get(0); String q2 = stemQuery.get(1); p1 = searchWord(q1); p2 = searchWord(q2); } switch (operator) { case "&": docIdResultsBoolean = intersect(p1, p2); break; case "|": docIdResultsBoolean = union(p1, p2); break; } tempResults.addAll(docIdResultsBoolean); } else { docIdResults.clear(); docIdResultsBoolean.clear(); parser.clearStemmerFile(); ArrayList<String> p1 = temp; ArrayList<String> p2 = new ArrayList<String>(); String operator = ""; if (query.contains("&")) { operator = "&"; query = query.replaceAll("&", " "); stemQuery = parser.stemLine(query); p2 = searchWord(stemQuery.get(0)); } else if (query.contains("|")) { operator = "|"; query = query.replaceAll("\\|", " "); stemQuery = parser.stemLine(query); p2 = searchWord(stemQuery.get(0)); } switch (operator) { case "&": docIdResultsBoolean = intersect(p1, p2); break; case "|": docIdResultsBoolean = union(p1, p2); break; } tempResults.addAll(docIdResultsBoolean); } return tempResults; }
9
@Test public void testSubgroupsOrder() { Collection<Symmetry4D> groups = Symmetry4D.getSymmetries(); int subgroupCounter; boolean isSubgroup; Collection<Rotation4D> groupMembers; Collection<? extends Symmetry<Point4D>> subgroups; for (Symmetry4D g : groups) { subgroupCounter = 0; subgroups = g.subgroups(); groupMembers = Symmetry4D.groups.get(g); for (Symmetry4D f : groups) { isSubgroup = true; for (Rotation4D rot : Symmetry4D.groups.get(f)) { if (!groupMembers.contains(rot)) { isSubgroup = false; break; } } if (isSubgroup) { subgroupCounter++; assertTrue(subgroups.contains(f)); } } assertEquals(subgroupCounter, g.subgroups().size()); } }
6
public static void addObservers(Game.Builder b) { InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); while (true) { printObservers(); /// int opt = getUserOption(br, 1, 4); /// switch (opt) { case 1: b.addObserver(new WinnerObserver()); break; case 2: b.addObserver(new AcumulatedObserver()); break; case 3: b.addObserver(new IndividualRollObserver()); break; case 4: return; } } }
5
public void testInverted() { m_Filter = getFilter("1,4,2-3"); ((TimeSeriesTranslate)m_Filter).setInvertSelection(true); Instances result = useFilter(); // Number of attributes shouldn't change assertEquals(m_Instances.numAttributes(), result.numAttributes()); assertEquals(m_Instances.numInstances() - 1, result.numInstances()); // Check conversion looks OK for (int i = 0; i < result.numInstances(); i++) { Instance in = m_Instances.instance(i + 1); Instance out = result.instance(i); for (int j = 0; j < result.numAttributes(); j++) { if ((j != 4) && (j != 5)&& (j != 6)) { if (in.isMissing(j)) { assertTrue("Nonselected missing values should pass through", out.isMissing(j)); } else if (result.attribute(j).isString()) { assertEquals("Nonselected attributes shouldn't change. " + in + " --> " + out, m_Instances.attribute(j).value((int)in.value(j)), result.attribute(j).value((int)out.value(j))); } else { assertEquals("Nonselected attributes shouldn't change. " + in + " --> " + out, in.value(j), out.value(j), TOLERANCE); } } } } }
7
public ShortestPaths getShortestPaths() { // Initialize level 0 of the weights pathWeights = new double[graph.vertices()][graph.vertices()][graph.vertices()]; for (int i = 0; i < graph.vertices() - 1; i++) { for (int j = 0; j < graph.vertices() - 1; j++) { if (i == j) { pathWeights[i][j][0] = 0; continue; } Edge edge = graph.getEdge(i + 1, j + 1); if (edge != null) { pathWeights[i][j][0] = edge.weight; } else { pathWeights[i][j][0] = Double.POSITIVE_INFINITY; } } } step(0); // Calculate weights until k-1 for (int k = 1; k < graph.vertices() - 1; k++) { for (int i = 0; i < graph.vertices() - 1; i++) { for (int j = 0; j < graph.vertices() - 1; j++) { double previousWeight = pathWeights[i][j][k - 1]; double x = pathWeights[i][k][k - 1] + pathWeights[k][j][k - 1]; double winner = Math.min(previousWeight, x); pathWeights[i][j][k] = winner; } } step(k); } int k = graph.vertices() - 1; ShortestPaths shortestPaths = new ShortestPaths(graph.vertices()); // Last round with filling result for (int i = 0; i < graph.vertices(); i++) { for (int j = 0; j < graph.vertices(); j++) { double previousWeight = pathWeights[i][j][k - 1]; double x = pathWeights[i][k][k - 1] + pathWeights[k][j][k - 1]; double winner = Math.min(previousWeight, x); pathWeights[i][j][k] = winner; shortestPaths.add(i + 1, j + 1, new ShortestPath(winner, new int[]{})); } } step(k); return shortestPaths; }
9
public static JMenuBar createMenuBar() { JMenuBar menuBarUpper = new JMenuBar(); //define and initialized menuBarUpper menuBarUpper.setBackground(new Color(windowColor)); f.setJMenuBar(menuBarUpper); //add the menuBarUpper to the frame JMenu fileMenu = new JMenu("File"); //create the "file" menu JMenu insertMenu = new JMenu("Insert"); JMenu toolsMenu = new JMenu("Tools"); JMenu HelpMenu = new JMenu("Help"); //create "help" menu menuBarUpper.add(fileMenu); //add the "file" menu to the bar menuBarUpper.add(insertMenu); menuBarUpper.add(toolsMenu); menuBarUpper.add(HelpMenu); //add "help" menu to the bar JMenuItem newItem = new JMenuItem("New"); newItem.setAccelerator(KeyStroke.getKeyStroke('N', KeyEvent.CTRL_DOWN_MASK)); /* JMenuItem loadItem = new JMenuItem("Load"); //create the open loadItem.setAccelerator(KeyStroke.getKeyStroke('O', KeyEvent.CTRL_DOWN_MASK)); */ final JMenuItem loadDataItem = new JMenuItem("Load Data"); //del final JMenuItem saveItem = new JMenuItem("Save"); //create the save saveItem.setAccelerator(KeyStroke.getKeyStroke('S', KeyEvent.CTRL_DOWN_MASK)); JMenuItem exit = new JMenuItem("Exit"); //create the exit final JMenuItem computePLEItem = new JMenuItem("Compute PLE"); final JMenuItem insertAPItem = new JMenuItem("Insert AP"); final JMenuItem SigmaItem = new JMenuItem("Insert Sigma"); final JMenuItem manageAPsItem = new JMenuItem("Manage Access Points"); final JMenuItem changeScaleItem = new JMenuItem("Change map scale"); final JMenuItem smoothResItem = new JMenuItem("Smooth resolution"); final JMenuItem HAPsItem = new JMenuItem("hypothetical AP's"); JMenuItem aboutItem = new JMenuItem("About WiMAP"); //create the about newItem.setToolTipText("New project"); //tool tip (on mouse hover) // loadItem.setToolTipText("Open Floor Plan"); //tool tip (on mouse hover) saveItem.setToolTipText("Save Map"); //tool tip (on mouse hover) exit.setToolTipText("Exit application"); //tool tip (on mouse hover) smoothResItem.setToolTipText("Effects speed"); //?? fileMenu.add(newItem); //add the new to the "file" menu // fileMenu.add(loadItem); //add the open to the "file" menu fileMenu.add(loadDataItem); fileMenu.add(saveItem); //add the save to the "file" menu fileMenu.add(exit); //add the exit to the "file" menu insertMenu.add(insertAPItem); insertMenu.add(SigmaItem); insertMenu.add(HAPsItem); toolsMenu.add(computePLEItem); toolsMenu.add(manageAPsItem); toolsMenu.add(changeScaleItem); toolsMenu.add(smoothResItem); HelpMenu.add(aboutItem); //add the about to the "Help" menu /*******************************File Menu******************************************/ // NEW newItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { try { newActionPerformed (event); } catch (Exception e) { return; } saveItem.setEnabled(true); loadDataItem.setEnabled(true); insertAPItem.setEnabled(true); computePLEItem.setEnabled(true); manageAPsItem.setEnabled(true); changeScaleItem.setEnabled(true); smoothResItem.setEnabled(true); HAPsItem.setEnabled(true); SigmaItem.setEnabled(true); } }); // OPEN /* loadItem.addActionListener(new ActionListener() { //action listener for open public void actionPerformed(ActionEvent event) { boolean flag = true ; try { openActionPerformed (event); } catch (Exception e) { flag = false ; } saveItem.setEnabled(flag); } }); */ loadDataItem.addActionListener(new ActionListener() { //action listener for open public void actionPerformed(ActionEvent event) { try { loadtextActionPerformed (event); } catch (Exception e) { return; } saveItem.setEnabled(true); } }); // SAVE saveItem.addActionListener(new ActionListener() { //action listener for open public void actionPerformed(ActionEvent event) { saveActionPerformed (event); } }); saveItem.setEnabled(false); // EXIT exit.addActionListener(new ActionListener() { //action listener for exit public void actionPerformed(ActionEvent event) { System.exit(0); } }); /*******************************Tool Menu******************************************/ computePLEItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { panelCanvas.compute_n(); } }); computePLEItem.setEnabled(false); manageAPsItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { new MngAP(); } }); manageAPsItem.setEnabled(false); insertAPItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { try { insertapdialog = new InsertAPDialog(panelCanvas); insertapdialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); insertapdialog.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); insertAPItem.setEnabled(false); SigmaItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { panelCanvas.InsertSigma(); } }); changeScaleItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { panelCanvas.removeMouseListener(panelCanvas.samplingML); JOptionPane.showMessageDialog(null, "To rescale\nClick on two points and enter the real distance between them in meters" ); panelCanvas.addMouseListener(panelCanvas.scalingML); } }); changeScaleItem.setEnabled(false); smoothResItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { try { resolutionDialog dialog = new resolutionDialog(panelCanvas); dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); dialog.setVisible(true); } catch (Exception e) { e.printStackTrace(); } /*try { String input = JOptionPane.showInputDialog(null, "Enter size of square in pixels", ""); // ?? if (panelCanvas.setSmoothRes(Integer.parseInt(input))) JOptionPane.showMessageDialog(null, "New smooth Resolution : " + panelCanvas.getSmoothRes()); else JOptionPane.showMessageDialog(null, "Invalid input, will restore default resolution\nSmooth Resolution: " + panelCanvas.getSmoothRes()); } catch (Exception e) { e.printStackTrace(); }*/ } }); smoothResItem.setEnabled(false); HAPsItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { panelCanvas.H_APs(); } }); HAPsItem.setEnabled(false); /*******************************Help Menu******************************************/ aboutItem.addActionListener(new ActionListener() { //action listener for about public void actionPerformed(ActionEvent event) { aboutActionPerformed (event); } }); return menuBarUpper ; }
4
public VirtualSequenceNode(Property p,PropertyTree parent,Property pPos,Property pTot) { super(p,parent); pPosition=pPos; pTotal=pTot; }
0
private void indent(final PrintWriter out, final int indent) { for (int i = 0; i < indent; i++) { out.print(" "); } }
1
public void draw(Graphics g, GameContainer gc) { gc.getGraphics().setBackground(sky); int minx = (int) -Math.ceil(drawx/16); int maxx = (int) (Math.ceil(LostAdventure.screenwidth/16))+minx+2; int miny = (int) -Math.ceil(drawy/16); int maxy = (int) (Math.ceil(LostAdventure.screenheight/16))+miny+2; if(minx < 0) { minx = 0; } if(maxx > width) { maxx = width; } if(miny < 0) { miny = 0; } if(maxy > height) { maxy = height; } for(int x=minx; x<maxx; x++) { for(int y=miny; y<maxy; y++) { if(map[x][y].blockimage != null) { map[x][y].blockimage.draw(drawx+x*blocksize, drawy+y*blocksize); } else if(map[x][y].blockcolor != null) { g.setColor(map[x][y].blockcolor); g.fillRect(drawx+x*blocksize, drawy+y*blocksize, blocksize, blocksize); } } } }
8
public ProfileInfo Get_DataObj(ProfileInfo DataObj) { //System.out.println("ProfileDAO.Get_DataObj()"); ProfileInfo profileObj = (ProfileInfo)DataObj; String sql = "select * from profile WHERE `Profile_Name`=?"; try { con = getConnection(); pstmt = con.prepareStatement(sql); pstmt.setString(1, profileObj.getProfileName()); rs = pstmt.executeQuery(); while (rs.next()) { profileObj = new ProfileInfo(); profileObj.setProfileName( rs.getString("Profile_name")); profileObj.setVideoWidth( rs.getString("Video_Width")); profileObj.setVideoHeight( rs.getString("Video_Height")); profileObj.setVideoFPS( rs.getString("Video_FPS")); profileObj.setVideoBitrate( rs.getString("Video_Bitrate")); profileObj.setVideoPreset( rs.getString("Video_Preset")); profileObj.setAudioCodec( rs.getString("Audio_Codec")); profileObj.setAudioBitrate( rs.getString("Audio_Bitrate")); profileObj.setAudioSamplerate( rs.getString("Audio_SampleRate")); } } catch (SQLException e) { e.printStackTrace(); } finally { try { if (rs != null) rs.close(); if (pstmt != null) pstmt.close(); if (con != null) con.close(); } catch (SQLException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } return profileObj; }
7
private int getScore(List<Integer[]> Hand){ int s = 0, a = 0; for (Integer[] i : Hand){ if (i[1] > 9) s += 10; else if (i[1] <= 9 && i[1] > 0) s += i[1] + 1; else if (i[1] == 0) a += 1; } for (int i = 0; i < a; i++){ if (s + 11 <= 21) s += 11; else s++; } return s; }
7
private int randomSwitchDirection() { int i; i = (int) Math.floor(Math.random() * 10 + 1); if (i > 5) { return -1; } else { return 1; } }
1
private static int partie(mode type) { int a, b; int i; int rep[] = new int[2]; int faute; //générer des nombre au hasard a = generate(); b = generate(); faute = 0; //calculer la réponse attendu switch(type) { case ADDITION: rep[0] = a+b; break; case SOUSTRACTION: rep[0] = a-b; break; case MULTIPLICATION: break; case DIVISION: break; } //demander la réponse, le joueur à plusieurs chance for(i = 0; i<CHANCE; i++) { rep[1] = Integer.parseInt(JOptionPane.showInputDialog(a+(type==mode.ADDITION?"+":"-")+b+"=")); //quitter la boucle si la bonne réponse est entré if(rep[0] == rep[1]) { JOptionPane.showMessageDialog(null, "Félicitations, vous avez la bonne réponse à l'expression arithmétique."); i = CHANCE; } //augmenter le nombre de faute si une mauvaise réponse est entré else { JOptionPane.showMessageDialog(null, "Désolé, vous n'avez pas la bonne réponse."); faute++; } } //retourner le nombre de faute durant la partie return faute; }
7
boolean matchbracketclass(int c, int poff, int ec) { boolean sig = true; if (p.luaByte(poff + 1) == '^') { sig = false; poff++; } while (++poff < ec) { if (p.luaByte(poff) == L_ESC) { poff++; if (match_class(c, p.luaByte(poff))) return sig; } else if ((p.luaByte(poff + 1) == '-') && (poff + 2 < ec)) { poff += 2; if (p.luaByte(poff - 2) <= c && c <= p.luaByte(poff)) return sig; } else if (p.luaByte(poff) == c) return sig; } return !sig; }
9
boolean allowMove(int dx, int dy) { int nx = x+dx; int ny = y+dy; int nx2 = x2+dx; int ny2 = y2+dy; int i; for (i = 0; i != sim.elmList.size(); i++) { CircuitElm ce = sim.getElm(i); if (ce.x == nx && ce.y == ny && ce.x2 == nx2 && ce.y2 == ny2) return false; if (ce.x == nx2 && ce.y == ny2 && ce.x2 == nx && ce.y2 == ny) return false; } return true; }
9
public void purchase(Integer key, Player player) { switch (key) { case KeyEvent.VK_1: if (player.decreaseCredits(shieldsPrice)) { shieldsPrice += player.getMaxHP()* 3; player.increaseMaxHP(5); player.setHitpoints(player.getMaxHP()); break; } case KeyEvent.VK_2: if (player.decreaseCredits(weaponPrice)) { weaponPrice += player.getDamage() * 10; player.increaseDamage(1); break; } case KeyEvent.VK_3: if (player.decreaseCredits(maneuverabilityPrice)) { maneuverabilityPrice += 50 - player.getRotationTime(); player.decreaseRotationTime(5); break; } case KeyEvent.VK_4: if (player.decreaseCredits(boostersPrice)) { boostersPrice += (player.getSpeed() * 100) * 2; player.increaseMaxSpeed(0.015f); player.setSpeed(player.getMaxSpeed()); break; } } }
8
public static void printResult(String result, String ...spacer_str) { String spacer = getSingleDefault(spacer_str, "-"); int longest_line_length = 1; String[] lines = result.split("\n"); for (int l=0; l<lines.length; l++) { longest_line_length = Math.max(longest_line_length, lines[l].length()); } String header_footer = multiplyString(spacer, longest_line_length); System.out.println(header_footer); System.out.println(result); System.out.println(header_footer); }
1
private void beginListening(String address, int port) { Socket s; try { s = new Socket(address, port); } catch (UnknownHostException ex) { onUnsuccessfulConnection(); return; } catch (IOException ex) { onUnsuccessfulConnection(); return; } server = prepareSocketContainer(s); onSuccessfulConnection(); InputStream cstream; try { cstream = server.getSocket().getInputStream(); } catch (IOException io) { System.out.println("Connection failed to be made with " + server.getSocket()); return; } GenericDataInput gdis = new StreamWrapperDataInputStream(cstream); while (true) { //c.getSocket().getInputStream(); //check if the socket is STILL ALIVE!! byte sig = (byte) gdis.readByte(); if (sig == -1) { onDisconnect(); return; } boolean caught = onPacketRecieved(sig, gdis); //System.out.println("Finished handling packet "+sig); if (!caught) { onUnhandledByte(sig, gdis); } } }
6
public static FilterConfig XML2java(Element root) { FilterConfig filterConfig = new FilterConfig(); Iterator rootIter = root.elementIterator(); while (rootIter.hasNext()) { Element element = (Element) rootIter.next(); if (element.getName().equals("source")) { filterConfig.setSource(PerserUtil.parserSource(element)); } else if (element.getName().equals("dimension")) { Iterator<Element> elementsubIter = element.elementIterator(); while (elementsubIter.hasNext()) { filterConfig.getDimension().add( PerserUtil.parserDimension(elementsubIter.next())); } } else if (element.getName().equals("measurement")) { filterConfig.setMeasurement(PerserUtil .parserMeasurement(element)); } else if (element.getName().equals("pivot")) { filterConfig.getPivot().add(PerserUtil.parserPivot(element)); } else if (element.getName().equals("profile")) { filterConfig.getProfile().setName(element.attributeValue("name")); Iterator<Element> elementsubIter = element.elementIterator(); while (elementsubIter.hasNext()) { filterConfig.getProfile().setPivots(PerserUtil.parserPivots(elementsubIter.next())); } } } return filterConfig; }
8
private static List<String> parse(String s) { List<String> keywords = new ArrayList<String>(); StringBuilder buff = new StringBuilder(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (Character.isLetter(c) || Character.isDigit(c)) { buff.append(Character.toLowerCase(c)); } else { String keyword = buff.toString(); if (keyword.length() > 0 && !ignoredKeywords.contains(keyword)) { keywords.add(keyword); } buff.setLength(0); } } return keywords; }
5
public void setResponse(Object response) { this.response = response; }
0
public long LCM(FactorTree other){ FactorTree lcm = new FactorTree(); for (long n : this.keySet()){ if (other.containsKey(n)){ int powerA = this.get(n); int powerB = other.get(n); int highest = (powerA<=powerB) ? powerB : powerA; lcm.put(n, highest); } else { lcm.put(n, this.get(n)); } } for (long n : other.keySet()){ if (!this.containsKey(n)){ lcm.put(n, other.get(n)); } } return lcm.getProduct(); }
5
public Traffic(int yStartingPos){ speed = (int)(Math.random() * 9 + 5); this.yStartingPos = yStartingPos; //randomly assign colours to each new car generated r = (int)(Math.random() * 255 + 1); g = (int)(Math.random() * 255 + 1); b = (int)(Math.random() * 255 + 1); trafficColor = new Color(r,g,b); r2 = (int)(Math.random() * 255 + 1); g2= (int)(Math.random() * 255 + 1); b2 = (int)(Math.random() * 255 + 1); roofColor = new Color(r2,g2,b2); width = FrogsterConstants.TRAFFIC_WIDTH; height = FrogsterConstants.TRAFFIC_HEIGHT; if(yStartingPos == 1){ y = 310; x = 0; }else if(yStartingPos == 2){ y = 520; x = FrogsterConstants.JPANEL_SIZE - width; }else if(yStartingPos == 3){ y = 450; x = 0; }else{ y = 380; x = FrogsterConstants.JPANEL_SIZE - width; } trafficRectangle = new Rectangle(x,y,width,height); }
3
public void execute() throws IOException { try { // Read the first 8192 bytes. // The full header should fit in here. // Apache's default header limit is 8KB. // Do NOT assume that a single read will get the entire header at once! byte[] buf = new byte[BUFSIZE]; splitbyte = 0; rlen = 0; { int read = inputStream.read(buf, 0, BUFSIZE); if(read == -1){ // socket was been closed throw new SocketException("NanoHttpd Shutdown"); } while (read > 0) { rlen += read; splitbyte = findHeaderEnd(buf, rlen); if (splitbyte > 0) break; read = inputStream.read(buf, rlen, BUFSIZE - rlen); } } if (splitbyte < rlen) { ByteArrayInputStream splitInputStream = new ByteArrayInputStream(buf, splitbyte, rlen - splitbyte); SequenceInputStream sequenceInputStream = new SequenceInputStream(splitInputStream, inputStream); inputStream = sequenceInputStream; } parms = new HashMap<String, String>(); headers = new HashMap<String, String>(); // Create a BufferedReader for parsing the header. BufferedReader hin = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(buf, 0, rlen))); // Decode the header into parms and header java properties Map<String, String> pre = new HashMap<String, String>(); decodeHeader(hin, pre, parms, headers); method = Method.lookup(pre.get("method")); if (method == null) { throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Syntax error."); } uri = pre.get("uri"); // Ok, now do the serve() Response r = serve(this); if (r == null) { throw new ResponseException(Response.Status.INTERNAL_ERROR, "SERVER INTERNAL ERROR: Serve() returned a null response."); } else { r.setRequestMethod(method); r.send(outputStream); } } catch(SocketException e) { // throw it out to close socket object (finalAccept) throw e; } catch (IOException ioe) { Response r = new Response(Response.Status.INTERNAL_ERROR, MIME_PLAINTEXT, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage()); r.send(outputStream); safeClose(outputStream); } catch (ResponseException re) { Response r = new Response(re.getStatus(), MIME_PLAINTEXT, re.getMessage()); r.send(outputStream); safeClose(outputStream); } finally { tempFileManager.clear(); } }
9
private String[] strinArrayProp(Properties props, String name, String[] defaultValue) { List<String> values = new ArrayList<String>(); for (int i = 0; i < 50; ++i) { String val = props.getProperty(name + "." + i); if (val != null) { values.add(val); } } if (values.isEmpty()) { return defaultValue; } return values.toArray(new String[values.size()]); }
3
public void writeNested(Input child, Element input){ input.appendChild(input); if(child instanceof And){ And casted = (And) child; input.setAttribute("name", "And"); Boolean x = casted.isOptional(); input.setAttribute("optional", x.toString()); for(int i = 0; i < casted.getConditions().size(); i++){ writeNested(casted.getConditions().get(i), input); } } else if(child instanceof Or){ Or casted = (Or) child; input.setAttribute("name", "Or"); Boolean x = casted.isOptional(); input.setAttribute("optional", x.toString()); for(int i = 0; i < casted.getConditions().size(); i++){ writeNested(casted.getConditions().get(i), input); } } else if(child instanceof HasCategory){ HasCategory casted = (HasCategory) child; input.setAttribute("name", "HasCategory"); input.setAttribute("category", casted.getCategory().getName()); Boolean x = casted.isOptional(); input.setAttribute("optional", x.toString()); } else if(child instanceof HasChild){ HasChild casted = (HasChild) child; input.setAttribute("name", "HasChild"); Boolean x = casted.isOptional(); input.setAttribute("optional", x.toString()); input.setAttribute("var", casted.getKey()); writeNested(casted.getCondition(), input); } else if(child instanceof HasConcept){ HasConcept casted = (HasConcept) child; input.setAttribute("name", "HasConcept"); } else if(child instanceof HasFeature){ HasFeature casted = (HasFeature) child; input.setAttribute("name", "HasFeature"); } }
8
static public void copyParamValues(Data source, Data dest) { double[] paramValueArray = new double[source.getParamValues().length]; for (int i = 0; i < paramValueArray.length; i++) { paramValueArray[i] = source.getParamValues()[i]; } dest.setParamValues(paramValueArray); dest.setBestParamData(paramValueArray); }
1
public static void main(String[] args) { // TODO code application logic here try{ //Server soket oluşturduk. ServerSocket sSocket=new ServerSocket(21500); System.out.printf("Server basladi."+" " + new Date()+"\n"); //bağlantı isteklerini dinlemeye aldık. while(true){ Socket sckt=sSocket.accept(); DataInputStream inputClient=new DataInputStream(sckt.getInputStream()); DataOutputStream outputClient=new DataOutputStream(sckt.getOutputStream()); //Burada artık işlem yapmaya başladık // Clienttan girilen yarıçapı alıp alanı bulup //tekrar Clienta yolluyoruz. String a = inputClient.readUTF(); if(a.equals("istek 1")){ System.out.println("Karakter sayisi gonderildi.\n"); int sayi = new File("folder").listFiles().length; outputClient.writeUTF(String.valueOf(sayi)); } if(a.equals("istek 2")){ System.out.println("Skor siralamasi gonderildi.\n"); //System.out.println("Ev sayisi hesaplaniyor."); //System.out.println("Ev sayisi gonderildi."); //int sayi = new File("/home/samp/HKDeathMatch/scriptfiles/PPC_Housing").listFiles().length; //outputClient.writeUTF(String.valueOf(sayi)); getScore g = new getScore(); g.doit(); Map<Integer, String> getTree = new TreeMap<Integer,String>(Collections.reverseOrder()); getTree.putAll(g.getTreeMap(g.treeMap)); //outputClient.writeUTF(String.valueOf(getTree.size())); for (Map.Entry entry : getTree.entrySet()) { //System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue()); outputClient.writeUTF(entry.getKey()+" "+entry.getValue()); } } if(a.equals("istek 3")){ System.out.println("Para siralamasi gonderildi.\n"); //System.out.println("Ev sayisi hesaplaniyor."); //System.out.println("Ev sayisi gonderildi."); //int sayi = new File("/home/samp/HKDeathMatch/scriptfiles/PPC_Housing").listFiles().length; //outputClient.writeUTF(String.valueOf(sayi)); getMoney gm = new getMoney(); gm.doit(); Map<Integer, String> getTreeMoney = new TreeMap<Integer,String>(Collections.reverseOrder()); getTreeMoney.putAll(gm.getTreeMap(gm.treeMap)); //outputClient.writeUTF(String.valueOf(getTree.size())); for (Map.Entry entry : getTreeMoney.entrySet()) { //System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue()); outputClient.writeUTF(entry.getKey()+" "+entry.getValue()); } } if(a.equals("istek 4")){ System.out.println("Online sure siralamasi gonderildi.\n"); //System.out.println("Ev sayisi hesaplaniyor."); //System.out.println("Ev sayisi gonderildi."); //int sayi = new File("/home/samp/HKDeathMatch/scriptfiles/PPC_Housing").listFiles().length; //outputClient.writeUTF(String.valueOf(sayi)); getOnlineTime go = new getOnlineTime(); go.doit(); Map<Integer, String> getTreeOnline = new TreeMap<Integer,String>(Collections.reverseOrder()); getTreeOnline.putAll(go.getTreeMap(go.treeMap)); //outputClient.writeUTF(String.valueOf(getTree.size())); for (Map.Entry entry : getTreeOnline.entrySet()) { //System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue()); outputClient.writeUTF(entry.getKey()+" "+entry.getValue()); } } } } catch(IOException e){ System.err.println(e); } }
9
@Override public void stateChanged(ChangeEvent e) { JSlider source = (JSlider)e.getSource(); if (!source.getValueIsAdjusting()) { jeu.setTimerDifficulte(source.getValue()); level.setText(String.valueOf(source.getValue())); statistique.setNiveau(source.getValue()); } }
1
private int[] computeSkirt(TPoint[] points, int width) { int[] skirt = new int[width]; for (int i = 0; i < width; i++) { //impossibly high value int minY = 5; for (int j = 0; j < points.length; j++) { TPoint currentPoint = points[j]; // if point is in right column if (currentPoint.x == i) { if (currentPoint.y < minY) minY = currentPoint.y; } } skirt[i] = minY; } return skirt; }
4
public void move() { displacementX += xIncrement*constantAcc; displacementY += yIncrement*constantAcc; if (displacementX > box.resolution().width - 5 - 150 || displacementX < 0) { xIncrement = xIncrement *(-1); this.image=box.selectPokemon(); } if (displacementY >box.resolution().height - 30 - 150 || displacementY <0) { yIncrement = yIncrement*(-1); this.image=box.selectPokemon(); } }
4
int distToPiece(Space[] set, int n, Piece p){ int d = 0; for(int i=n-1;i>=0;i--){ if(set[i].getPiece()==p){ d=n-i; break; } } for(int i=n+1;i<set.length;i++){ if(set[i].getPiece()==p){ if(d==0 || i-n<d) d = i-n; break; } } return d; }
6
public void setColor(int color) { this.color = color; switch (color) { case EMPTY_BOLL: image = new ImageIcon(NULL_BOLL); break; case BIG_RED: image = new ImageIcon(BIG_RED_BOLL); break; case BIG_GREEN: image = new ImageIcon(BIG_GREEN_BOLL); break; case BIG_CYAN: image = new ImageIcon(BIG_CYAN_BOLL); break; case BIG_PINK: image = new ImageIcon(BIg_PINK_BOLL); break; case SMALL_RED: image = new ImageIcon(SMALL_RED_BOLL); break; case SMALL_GREEN: image = new ImageIcon(SMALL_GREEN_BOLL); break; case SMALL_CYAN: image = new ImageIcon(SMALL_CYAN_BOLL); break; case SMALL_PINK: image = new ImageIcon(SMALL_PINK_BOLL); break; default: System.out.println("Error"); break; } setIcon(image); }
9
@Override public void mouseReleased(MouseEvent e) { switch(e.getButton()) { case MouseEvent.BUTTON1: //Left click //System.out.println("X: " + cX + ", Y: " + cY + "\t"); selected = Game.map.getUnit(pX, pY); if(Game.gui.canSelect(selected)) { walkList = new ArrayList<>(Game.paths.getWalk()); Game.paths.clearPaths(); //if(Game.inGrid(cX, cY)) Shouldn't need this check, move function already performs check //System.out.println("Moving unit"); selected.move(cX, cY, walkList); } canPath = false; Game.gui.update(selected); Game.gui.update(e.getX(), e.getY(), false, 1); //System.out.println("released left"); break; case MouseEvent.BUTTON2: //Middle click Game.gui.update(e.getX(), e.getY(), false, 2); //System.out.println("released middle"); break; case MouseEvent.BUTTON3: //Right click Game.gui.update(e.getX(), e.getY(), false, 3); //System.out.println("released right"); break; } }
4
@EventHandler public void onSelectMob(PlayerInteractFakeMobEvent event) { Player player = event.getPlayer(); FakeMob mob = event.getMob(); if (Cache.selectedMobs.containsKey(player) && Cache.selectedMobs.get(player) == null) { Cache.selectedMobs.put(player, mob); player.sendMessage(ChatColor.GREEN + "Mob " + ChatColor.GRAY + "#" + mob.getId() + ChatColor.GREEN + " selected!"); return; } if (event.getAction() == Action.RIGHT_CLICK && mob.haveShop()) mob.getShop().openShop(player, (mob.getCustomName() != null && !mob.getCustomName().isEmpty()) ? mob.getCustomName() : null); }
6
public void decrement() { count.decrementAndGet(); }
0
public IndexedModel toIndexedModel(){ IndexedModel result = new IndexedModel(); IndexedModel normalModel = new IndexedModel(); HashMap<ObjIndex, Integer> resultIndexMap = new HashMap<ObjIndex, Integer>(); HashMap<Integer, Integer> normalIndexMap = new HashMap<Integer, Integer>(); HashMap<Integer, Integer> indexMap = new HashMap<Integer, Integer>(); for(int i = 0 ; i < indices.size() ; i++){ ObjIndex currentIndex = indices.get(i); Vector3f currentPosition = positions.get(currentIndex.vertexIndex); Vector2f currentTexCoord; Vector3f currentNormal; if(hasTexCoords){ currentTexCoord = texCoords.get(currentIndex.texCoordIndex); }else{ currentTexCoord = new Vector2f(0,0); } if(hasNormals){ currentNormal = normals.get(currentIndex.normalIndex); }else{ currentNormal = new Vector3f(0,0,0); } Integer modelVertexIndex = resultIndexMap.get(currentIndex); if(modelVertexIndex == null){ modelVertexIndex = result.getPositions().size(); resultIndexMap.put(currentIndex, result.getPositions().size()); result.getPositions().add(currentPosition); result.getTexCoords().add(currentTexCoord); if(hasNormals){ result.getNormals().add(currentNormal); } } Integer normalmodelIndex = normalIndexMap.get(currentIndex.vertexIndex); if(normalmodelIndex == null){ normalmodelIndex = normalModel.getPositions().size(); normalIndexMap.put(currentIndex.vertexIndex, normalModel.getPositions().size()); normalModel.getPositions().add(currentPosition); normalModel.getTexCoords().add(currentTexCoord); normalModel.getNormals().add(currentNormal); } result.getIndices().add(modelVertexIndex); normalModel.getIndices().add(normalmodelIndex); indexMap.put(modelVertexIndex, normalmodelIndex); } if(!hasNormals){ normalModel.calcNormals(); for(int i = 0 ; i < result.getPositions().size() ; i++){ result.getNormals().add(normalModel.getNormals().get(indexMap.get(i))); } } return result; }
8
public ServerCli(){ _commands.add(new Command("Show Computers")); _commands.add(new Command("Show Time")); _commands.add(new Command("Show Version")); _commands.add(new Command("Exit")); }
0
private ArrayList<Integer> getColours() { ArrayList<Integer> answer = new ArrayList<Integer>(); int i = 0; while(i != colourList.size() && (answer.size() != g.getSolutionSize())) { int j = 0; ArrayList<Integer> temp = new ArrayList<Integer>(); //Guess 4 of one colour while (j != g.getSolutionSize()) { g.addToEndGuess(i); temp.add(i); j++; } //Add the guess to the guesses allGuesses.add(temp); //printArray(temp, false); //Do a check boolean correct = g.guessCheck(); //If correct then break if (correct) { answer = null; break; } //Check if this colour is contained //Need to look at hints //2 means correct pos //1 means correct colour ArrayList<Integer> hint = g.guessRes(); //System.out.println("Hint is "); //printArray(hint, true); allHints.add(hint); int x = 0; //If there was any correct colours we add to answer while (x != hint.size()) { //We got a correct colour if (hint.get(x) == 2) { answer.add(i); } x++; } //If we have 3 right colours and its the last colour to check if ((answer.size() == g.getSolutionSize() - 1) && (i == colourList.size() - 2)) { answer.add(i + 1); //System.out.println("Saved a guess!"); i++; } i++; } return answer; }
8
public void updateFileComboBox() { fileprojectNameComboBox.removeAllItems(); String[] file_projName_strArray = projectTableController.getProjNameComboBoxesData(); for(String str : file_projName_strArray) { fileprojectNameComboBox.addItem(str); } }
1
@SuppressWarnings("resource") public static boolean registerInstance() { // returnValueOnError should be true if lenient (allows app to run on network error) or false if strict. boolean returnValueOnError = true; // try to open network socket // if success, listen to socket for new instance message, return true // if unable to open, connect to existing and send new instance message, return false try { final ServerSocket socket = new ServerSocket(SINGLE_INSTANCE_NETWORK_SOCKET, 10, InetAddress.getLocalHost()); log.debug("Listening for application instances on socket " + SINGLE_INSTANCE_NETWORK_SOCKET); Thread instanceListenerThread = new Thread(new Runnable() { public void run() { boolean socketClosed = false; while (!socketClosed) { if (socket.isClosed()) { socketClosed = true; } else { try { Socket client = socket.accept(); BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream())); String message = in.readLine(); if (SINGLE_INSTANCE_SHARED_KEY.trim().equals(message.trim())) { log.debug("Shared key matched - new application instance found"); fireNewInstance(); } in.close(); client.close(); } catch (IOException e) { socketClosed = true; } } } } }); instanceListenerThread.start(); // listen } catch (UnknownHostException e) { log.error(e.getMessage(), e); return returnValueOnError; } catch (IOException e) { log.debug("Port is already taken. Notifying first instance."); try { Socket clientSocket = new Socket(InetAddress.getLocalHost(), SINGLE_INSTANCE_NETWORK_SOCKET); OutputStream out = clientSocket.getOutputStream(); out.write(SINGLE_INSTANCE_SHARED_KEY.getBytes()); out.close(); clientSocket.close(); log.debug("Successfully notified first instance."); return false; } catch (UnknownHostException e1) { log.error(e.getMessage(), e); return returnValueOnError; } catch (IOException e1) { log.error("Error connecting to local port for single instance notification"); log.error(e1.getMessage(), e1); return returnValueOnError; } } return true; }
8
public static void initializeCollisionGroups(Class<? extends GameObject> type, Class<? extends GameObject>[] list){ boolean isAbstract = Modifier.isAbstract(type.getModifiers()); System.out.println("\tInitializing group: " + type + " w/ " + list); if (isAbstract){ System.out.println("\t\tThis is an abstract class"); } for (Class<? extends GameObject> c : list){ CollisionGroup g = new CollisionGroup(type, c, isAbstract); if (addCollisionGroup(g)){ System.out.println("\tCollision group added: " + g); } else { System.out.println("\t******************\n******************ERROR: Collision group failed to add: " + g); } } }
6
public Boolean pretarate() { if (this.txt_num_estado.getText().matches("[1-9][0-9]*") && this.txt_num_simbolo.getText().matches("[1-9][0-9]*")) { if (this.txt_num_estado.getText().length() != 0 && this.txt_num_simbolo.getText().length() != 0) { modelTable.setColumnCount(Integer.parseInt(this.txt_num_simbolo.getText()) + 2); modelTable.setRowCount(Integer.parseInt(this.txt_num_estado.getText()) + 1); // this.table_trans.setTableHeader(); return true; } } return false; }
4
@Override public boolean equals(Object o){ Time time = (Time) o; if (this.hour == time.hour && this.min == time.min){ return true; } return false; }
2
@Override public final void update(final Observable o, final Object arg) { final HashMap<Program, Integer> unsorted = new HashMap<Program, Integer>(); final Vector<Entity> entities = new Vector<Entity>(field.getEntities()); for (final Entity entity : entities) { final Program program = entity.getProgram(); int amount = 1; if (unsorted.containsKey(program)) { amount += unsorted.get(program); } unsorted.put(program, amount); } final Vector<Entry<Program, Integer>> sorted = new Vector<Map.Entry<Program, Integer>>(unsorted.entrySet()); Collections.sort(sorted, this); data = sorted; for (final TableModelListener l : listener) { l.tableChanged(new TableModelEvent(this)); } }
3
private Boolean validateEvent(String eventName, List<MMTFieldValueHeader> fieldValueElements) throws MMTInitializationException { Boolean retval = true; if (this.getProtoConfig() == null) { throw new MMTInitializationException("Initialization Exception: getProtoConfig() returns null. A valid MMTRemoteProtocolConfig must be set."); } else if (this.getProtoConfig().getEventValidationLevel() != MMTProtocolConfig.NoEventValidation) { MMTEventConfig event = this.getProtoConfig().getEventByName(eventName); if (event == null) { throw new MMTInitializationException("Initialization Exception: Event name \"" + eventName + "\" is not registered. Each Event MUST be registered in order to be used."); } else if (this.getProtoConfig().getEventValidationLevel() == MMTProtocolConfig.CompleteEventValidation) { this.validateEventStructure(eventName, fieldValueElements); } } return retval; }
4
public static double erfc(double x) { double erfc = 1.0D; if (x != 0.0) { if (x == 1.0D / 0.0D) { erfc = 0.0D; } else { if (x >= 0) { erfc = 1.0D - Stat.incompleteGamma(0.5, x * x); } else { erfc = 1.0D + Stat.incompleteGamma(0.5, x * x); } } } return erfc; }
3
public void sendRequest(String resultObject, JSONRPC2Request jsonrpc2Request){ System.out.println(); System.out.println("Request: " +jsonrpc2Request.toJSONString()); String id = jsonrpc2Request.getID().toString(); URL serverURL = null; try { if(isDevelopment){ serverURL = new URL("http://" + InetAddress.getLocalHost().getHostAddress() + ":" + Constants.Http.PORT + "/"); System.out.println("Client is running in development"); }else{ serverURL = new URL("http://" + Constants.General.EXTERNAL_SERVER_IP + ":" + Constants.Http.PORT + "/"); System.out.println("Client is running in live"); } } catch (Exception e) { e.printStackTrace(); } System.out.println("ServerURL: " + serverURL.toString()); JSONRPC2Session mySession = new JSONRPC2Session(serverURL); JSONRPC2SessionOptions options = new JSONRPC2SessionOptions(); options.setConnectTimeout(10000); mySession.setOptions(options); JSONRPC2Response response = null; // Send request try { response = mySession.send(jsonrpc2Request); } catch (JSONRPC2SessionException e) { response = handleJSONRPC2Exception(e); } XStream xstream = new XStream(); xstream.aliasPackage("models", "core.test.models"); printResponse(response); String xmlString = null; Object returnedObject = null; xstream.alias("list", LinkedList.class); if(response.indicatesSuccess() && ((JSONObject)response.getResult()).get(Constants.Param.Status.STATUS).equals(Constants.Param.Status.SUCCESS)){ String test; if(resultObject != null){ test = (String) ((JSONObject)response.getResult()).get(resultObject); try { xmlString = deSerializeObject(String.class, test); returnedObject = xstream.fromXML(xmlString); } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } catch (ClassNotFoundException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } } }
8
public static String getOutboundMessage(Packets packet, String data){ String returned; returned = packet.id + "|" + data; return returned; }
0
@Override public void actionPerformed(ActionEvent arg0) { // TODO Auto-generated method stub synchronized (controller) { controller.notify(); } if ("VIEW LOG FILE".equals(start.getText())) { try { Runtime.getRuntime().exec( "notepad.exe src/Resurces/LogFile/Log.log"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if ("ABORT".equals(start.getText())){ for (TransportationTask t : transportationTask) { try { t.stop(); } catch (InterruptedException e) { // TODO Auto-generated catch block System.err.println("Run was stoped Hummen Operator"); } } controller.validation(); start.setText("VIEW LOG FILE"); } if ("START".equals(start.getText())) { start.setText("ABORT"); } }
6
private void move() { if(endValuesIndex >= values.size()) { endValuesIndex++; return; } // select next // move start to next stop of values change int compare = values.get(startValuesIndex).getEnd().compareTo( metric.removes(values.get(endValuesIndex).getEnd(), allocationDuration) ); if (compare <= 0) { // next stop of start is closer to current start than next stop of end startPoint = values.get(startValuesIndex).getEnd(); endPoint = metric.add(startPoint, allocationDuration); startValuesIndex++; if (compare == 0) { endValuesIndex++; } } else { endPoint = values.get(endValuesIndex).getEnd() ; startPoint = metric.removes(endPoint, allocationDuration); endValuesIndex++; } }
3
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub JSONObject jb = new JSONObject(); InputStreamReader reader = new InputStreamReader(request.getInputStream(), "utf-8"); String receivedString = ""; char[] buff = new char[1024]; int length = 0; while ((length = reader.read(buff)) != -1) { receivedString = new String(buff, 0, length); } try { JSONObject receivedObject = new JSONObject(receivedString); String userId = receivedObject.getString("userId"); JSONArray friends = receivedObject.getJSONArray("friends"); String groupName = receivedObject.getString("groupName"); try{ Mongo mongo =new Mongo(); DB scheduleDB = mongo.getDB("schedule"); DBCollection groupCollection = scheduleDB.getCollection("group_"+userId); DBObject groupDBObject = new BasicDBObject(); groupDBObject.put("groupName", groupName); WriteResult wr = groupCollection.save(groupDBObject); if(wr.getN() != 0){ jb.put("result", Primitive.DBSTOREERROR); }else{ int i; for(i =0; i < friends.length(); i++){ DBObject updateObject = new BasicDBObject(); DBObject member = new BasicDBObject(); String memberId = friends.getString(i); member.put("member", memberId); updateObject.put("$push", member); DBObject updateQuery = new BasicDBObject(); String groupId = groupDBObject.get("_id").toString(); updateQuery.put("_id", new ObjectId(groupId)); WriteResult wr2 =groupCollection.update( updateQuery, updateObject); if(wr2.getN() == 0){ jb.put("result", Primitive.DBSTOREERROR); break; } } if( i == friends.length()){ jb.put("result", Primitive.ACCEPT); jb.put("groupId", groupDBObject.get("_id").toString()); } } }catch(MongoException e){ jb.put("result", Primitive.DBCONNECTIONERROR); e.printStackTrace(); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } PrintWriter writer = response.getWriter(); writer.write(jb.toString()); writer.flush(); writer.close(); }
7
public Atdl4jWidget<?> getAtdl4jWidgetForParameter( ParameterT aParameterRef ) { if ( ( aParameterRef != null ) && ( getAtdl4jWidgetWithParameterMap() != null ) ) { Collection<Atdl4jWidget<?>> tempAtdl4jWidgetWithParameterMapValues = (Collection<Atdl4jWidget<?>>) getAtdl4jWidgetWithParameterMap().values(); for ( Atdl4jWidget<?> widget : tempAtdl4jWidgetWithParameterMapValues ) { if ( aParameterRef.equals( widget.getParameter() ) ) { return widget; } } } return null; }
8
public void paintSelectedIndex(Graphics g, Camera cam) { if (world != null && world.length > 0 && world[0] != null && world[0].length > 0) { // Draw index near selected tile: if (selectedTile_x >= 0 && selectedTile_x < world.length && selectedTile_y >= 0 && selectedTile_y < world[0].length) { String msg = "(" + selectedTile_x + "," + selectedTile_y + ")"; int fontSize = 20; g.setFontSize(fontSize); g.drawRect((int) ((selectedTile_x * width - cam.viewX) / cam.viewW * g.getWidth()), (int) ((selectedTile_y * height - cam.viewY) / cam.viewH * g.getHeight() - 0.9 * fontSize), (int) (fontSize * msg.length() * 0.48), fontSize, 255, 0, 0, 120); g.drawText(msg, selectedTile_x * width, selectedTile_y * height, 0x00ffff, cam); } }// End Sanity IF }
8
@Override public Binary get(Object key) { if (!(key instanceof Binary)) return null; final Binary bKey = (Binary) key; final byte[] keyData = bKey.getValue(); final int keySize = keyData.length; final int hash = Math.abs(hashFunction.apply(keyData)); final long offset = hash % partitionCount; // This is the location of the partition on which the entry key belongs long locationAddress = unsafe.getAddress(partitionAddress + (offset * addressSize)); // Skip if unallocated if (locationAddress == 0) return null; // Read how many entries we expect in this partition int entryCount = unsafe.getInt(locationAddress); // Move pointer past size int locationAddress += Integer.BYTES; for (long locationOffset = 0; locationOffset < entryCount; locationOffset++) { // Address of key within partition long keyAddress = unsafe.getAddress(locationAddress + (locationOffset * addressSize * 2)); // Get size of key int size = unsafe.getInt(keyAddress); // If size of this key is different than the one // we're looking for, continue.. if (size != keySize) continue; // Move pointer past size int keyAddress += Integer.BYTES; // Scan each byte to check for differences boolean isEqual = true; for (int keyOffset = 0; keyOffset < keySize; keyOffset++) { if (keyData[keyOffset] != unsafe.getByte(keyAddress + keyOffset)) { isEqual = false; break; } } // Check if we found the key if (isEqual) { long valueAddress = unsafe.getAddress(locationAddress + (locationOffset * addressSize * 2) + addressSize); // Check if this is a null value if (valueAddress == 0) return null; int valueSize = unsafe.getInt(valueAddress); byte[] valueData = new byte[valueSize]; // Move pointer past size int valueAddress += Integer.BYTES; for (int valueOffset = 0; valueOffset < valueSize; valueOffset++) { valueData[valueOffset] = unsafe.getByte(valueAddress + valueOffset); } return new Binary(valueData); } } return null; }
9
public static void main(String[] args) { PixelFormat pixelFormat = new PixelFormat(8, 8, 8); ContextAttribs attribs = new ContextAttribs(3, 2) .withForwardCompatible(true).withProfileCore(true); try { Display.setDisplayMode(new DisplayMode(1280, 720)); Display.create(pixelFormat, attribs); } catch (LWJGLException e) { e.printStackTrace(); System.exit(0); } exitOnGLError("Init"); Game game = new Game(1280,720); try { game.init(); } catch (Exception e) { System.out.println("Error initializing Game: " + e.getMessage()); e.printStackTrace(); System.exit(-1); } exitOnGLError("init"); long t1, t2; double delta = 0.0d; try { while (!Display.isCloseRequested()) { t1 = Sys.getTime(); game.update(delta); game.render(); Display.update(); exitOnGLError("Rendering"); t2 = Sys.getTime(); delta = ((double) (t2 - t1)) / Sys.getTimerResolution(); //debugging if(Keyboard.isKeyDown(Keyboard.KEY_SPACE)) delta *= 0.1d; } } catch (Exception e) { e.printStackTrace(); Display.destroy(); System.exit(-2); } game.cleanup(); Display.destroy(); }
5
public Boolean loadPlayer2() { boolean test = false; if (test || m_test) { System.out.println("Loader :: loadPlayer2() BEGIN"); } if (loadPlayer(getPlayer2File())) { setPlayer2(createPlayerType(m_playerInfo[PLAYER_TYPE_INDEX])); getPlayer2().setPlayerName(m_playerInfo[PLAYER_NAME_INDEX]); getPlayer2().setPlayerColour(new Color(Integer.parseInt( m_playerInfo[PLAYER_COLOR_INDEX]))); getPlayer2().setYourTurn(Boolean.parseBoolean( m_playerInfo[PLAYER_TURN_INDEX])); if (Boolean.parseBoolean(m_playerInfo[PLAYER_TURN_INDEX])) { getGame().setPlayerTurn(Game.PlayerTurn.PLAYER2); } } else { m_allValid = false; System.err.println("Error with player 2"); } if (test || m_test) { System.out.println("Loader :: loadPlayer2() END"); } return true; }
6
public void add(int element) { if(manyItems == data.length) { ensureCapacity((manyItems + 1)*2); } data[manyItems] = element; manyItems++; }
1
@RequestMapping(value="/usuario/cadastrarUsuario", method=RequestMethod.POST) public String cadastrarUsuario(@Valid Usuario usuario, BindingResult result, ModelMap model){ String mensagem = null; if(result.hasFieldErrors("nome") || result.hasFieldErrors("sobrenome") || result.hasFieldErrors("email") || result.hasFieldErrors("username") || result.hasFieldErrors("senha") || result.hasFieldErrors("confirmaSenha") ){ mensagem = "Erro ao cadastrar usuário!"; model.addAttribute("mensagemTitulo", mensagem); return "forward:/usuario"; }else{ try{ usuarioService.cadastrarUsuario(usuario); mensagem = "Usuário cadastrado com sucesso!"; } catch (ValidationException e) { mensagem = e.getMessage(); model.addAttribute("mensagemTitulo", mensagem); return "forward:/usuario"; } model.addAttribute("mensagemTitulo", mensagem); return "forward:/login/login"; } }
7
@SuppressWarnings("unchecked") @Override public void insertElementAt(E element, int index) { int size = getSize(); for(index = 0; index < size; index++) { if(comparator != null) { E o = getElementAt(index); if(comparator.compare(o, element) > 0) break; } else { Comparable c = (Comparable) getElementAt(index); if(c.compareTo(element) > 0) break; } } super.insertElementAt(element, index); if(index == 0 && element != null) setSelectedItem(element); }
6
@Override public void update(Observable observable, Object identifyer) { Warborn model = (Warborn)observable; if(identifyer!=null && identifyer.getClass()==Integer.class && (Integer)(identifyer)==1){ switch(model.getState()){ case STARTPHASE: new Thread(new StatePanel(model, frame, "Place Your Troops")).start(); break; case REINFORCEPHASE: new Thread(new StatePanel(model, frame, model.getCurrentPlayer().getName(), "Reinforce Your Troops")).start(); break; case BATTLEPHASE: new Thread(new StatePanel(model, frame, "Battle Phase")).start(); break; case MOVEPHASE: new Thread(new StatePanel(model, frame, "Troop Movement")).start(); break; } } }
7
public void zoneEventOccurred(String eventZone, int eventType) { if(Debug.localMouse) System.out.println("Event occurred of type: "+eventType+ " in zone: "+eventZone); double scaleFactor = 0.9; if(ZoneEvents.PRESS == eventType) { /* //----Horizontal scaling only testPanel.setLocation((int)((double)(testPanel.getX()* scaleFactor)), testPanel.getY()); testPanel.setSize((int)((double)(testPanel.getWidth()* scaleFactor)), testPanel.getHeight()); scaleColouredPanels(); myLMM.applyScaleFactor(scaleFactor, true, false); //-----Vertical scaling only testPanel.setLocation(testPanel.getX(), (int)((double)(testPanel.getY()*scaleFactor))); testPanel.setSize(testPanel.getWidth(), (int)((double)(testPanel.getHeight()*scaleFactor))); scaleColouredPanels(); myLMM.applyScaleFactor(scaleFactor, false, true); */ //-----Scaling in both directions testPanel.setLocation((int)((double)(testPanel.getX()*scaleFactor)), (int)((double)(testPanel.getY()*scaleFactor))); testPanel.setSize((int)((double)(testPanel.getWidth()*scaleFactor)), (int)((double)(testPanel.getHeight()*scaleFactor))); scaleColouredPanels(); myLMM.applyScaleFactor(scaleFactor, true, true); } if(ZoneEvents.RELEASE == eventType && eventZone == "Red Zone") { Zone zoneToModify = myLMM.retrieveZone("Red Zone"); zoneToModify.name = "SCHOOBLERIA"; //myLMM.removeZone("NonExistent Zone"); } }
4
private static int alphaBeta(Configuration conf, int alpha, int beta,byte depth,byte max){ if ((conf.whoWin() != 0) || (depth >= max)){ return evaluation(conf); } else{ int meilleur = Integer.MIN_VALUE; for (Configuration fconf : listeFils(conf)) { int suiv=-alphaBeta(fconf, -beta, -alpha, (byte) (depth+1),max); if (suiv > meilleur) { meilleur=suiv; if(meilleur > alpha){ alpha=meilleur; if (alpha >= beta) { return meilleur; } } } } return meilleur; } }
6
public static <T extends Enum<?>> T lookup(Map<String, T> lookup, String name, boolean fuzzy) { String testName = name.replaceAll("[ _]", "").toLowerCase(); T type = lookup.get(testName); if (type != null) { return type; } if (!fuzzy) { return null; } int minDist = Integer.MAX_VALUE; for (Map.Entry<String, T> entry : lookup.entrySet()) { final String key = entry.getKey(); if (key.charAt(0) != testName.charAt(0)) { continue; } int dist = getLevenshteinDistance(key, testName); if (dist >= minDist) { minDist = dist; type = entry.getValue(); } } if (minDist > 1) { return null; } return type; }
7
@Override public STAFResult execute(RequestInfo reqInfo) { STAFResult result = super.execute(reqInfo); if (result.rc == STAFResult.Ok) { CommandAction command = null; String parsedCommandName = (parseResult.numInstances() >= 2) ? parseResult.instanceName(2).toUpperCase() : null; LOG.info("Looking for command action with name " + parsedCommandName); if (parsedCommandName != null) { command = subCommands.get(parsedCommandName); } else { LOG.warning("No command specified"); } if (command != null) { result = command.execute(parseResult); } else { result = new STAFResult(STAFResult.InvalidParm, "No service command found."); } } return result; }
4
@Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final IslandLocation other = (IslandLocation) obj; if (!Objects.equals(this.location, other.location)) { return false; } return true; }
3
private void func_72145_a(World par1World, int par2, int par3, int par4, boolean par5, boolean par6, boolean par7, boolean par8) { if (par6 && !par8) { par1World.playSoundEffect((double)par2 + 0.5D, (double)par3 + 0.10000000000000001D, (double)par4 + 0.5D, "random.click", 0.4F, 0.6F); } else if (!par6 && par8) { par1World.playSoundEffect((double)par2 + 0.5D, (double)par3 + 0.10000000000000001D, (double)par4 + 0.5D, "random.click", 0.4F, 0.5F); } else if (par5 && !par7) { par1World.playSoundEffect((double)par2 + 0.5D, (double)par3 + 0.10000000000000001D, (double)par4 + 0.5D, "random.click", 0.4F, 0.7F); } else if (!par5 && par7) { par1World.playSoundEffect((double)par2 + 0.5D, (double)par3 + 0.10000000000000001D, (double)par4 + 0.5D, "random.bowhit", 0.4F, 1.2F / (par1World.rand.nextFloat() * 0.2F + 0.9F)); } }
8