text
stringlengths
14
410k
label
int32
0
9
public int minDistance(String word1, String word2){ int rowSize = word1.length(); int colSize = word2.length(); if(rowSize == 0){ return colSize; } if(colSize == 0){ return rowSize; } int res[][] = new int[rowSize+1][colSize+1]; for(int i=0; i<=rowSize; i++){ res[i][0] = i; } for(int j=0; j<=colSize; j++){ res[0][j] = j; } for(int i=1; i<=rowSize; i++){ for(int j=1; j<=colSize; j++){ if(word1.charAt(i-1) == word2.charAt(j-1)){ res[i][j] = res[i-1][j-1]; } else{ int addLetterToWord1 = res[i][j-1] + 1; int deleteFromWord1 = res[i-1][j] + 1; int replaceLetterInWord1 = res[i-1][j-1] + 1; int temp = addLetterToWord1 < deleteFromWord1 ? addLetterToWord1 : deleteFromWord1; res[i][j] = temp < replaceLetterInWord1 ? temp : replaceLetterInWord1; } } } return res[rowSize][colSize]; }
9
public static void main(String[] args) throws KeyNotUpdatedException, KeyNotFoundException { RepositoryUpdate theMerge = new RepositoryUpdate(); PlayerRepository<Schema.Player> repository = JacksonPlayerRepository.create("/master.player.json"); for(Schema.Player p : repository.getPlayers()) { for (Map.Entry<String,String> id : p.id.entrySet()) { Map<String,Player> repo = theMerge.index.get(id.getKey()); if (null == repo) { repo = Maps.newHashMap(); theMerge.index.put(id.getKey(),repo); } repo.put(id.getValue(),Schema.TRANSFORM.apply(p)); } } final FileBackedStore playerStore = new FileBackedStore(new File("")); PlayerStore.Reader in = playerStore.createReader(); String updates[] = { "mlb.players.json" , "espn.players.json" , "lahman.players.json" , "rotoworld.players.json" , "yahoo.players.json" }; for (String updateDatabase : updates) { Iterable<? extends Player> update = in.readPlayers(updateDatabase); update = Iterables.filter(update, Biography.HAS_BIO_FILTER); theMerge.merge(update); } PlayerStore.Writer out = playerStore.createWriter(SORT); out.writePlayers("update.missing.json", theMerge.missing); out.writePlayers("update.conflict.json", theMerge.conflicts); }
5
public static void ChooseCody () { if (Game.characterChoice == 1) { Game.CharacterOne = "Cody"; Game.CharacterOneHP = CharacterStats.CodyHP; Game.CharacterOneAttack = CharacterStats.CodyAttack; Game.CharacterOneMana = CharacterStats.CodyMana; Game.CharacterOneRegen = CharacterStats.CodyRegen; Game.MovesOne = CharacterMoves.CodyMoves; Game.MoveOneValue [0] = CharacterStats.CodyAttack; Game.MoveOneValue [1] = CharacterMoves.Calm; Game.MoveOneValue [2] = CharacterMoves.FlyingKick; Game.MoveOneValue [3] = CharacterMoves.FacePalm; Game.MoveOneValue [4] = CharacterMoves.Calculus; Game.MoveOneCost [0] = CharacterMoves.AttackCost; Game.MoveOneCost [1] = CharacterMoves.CalmCost; Game.MoveOneCost [2] = CharacterMoves.FlyingKickCost; Game.MoveOneCost [3] = CharacterMoves.FacePalmCost; Game.MoveOneCost [4] = CharacterMoves.CalculusCost; Game.OptionsOne [0] = "Attack (" + CharacterMoves.AttackCost + " mana)"; Game.OptionsOne [1] = "Calm (" + CharacterMoves.CalmCost + " mana)"; Game.OptionsOne [2] = "FlyingKick (" + CharacterMoves.FlyingKickCost + " mana)"; Game.OptionsOne [3] = "FacePalm (" + CharacterMoves.FacePalmCost + " mana)"; Game.OptionsOne [4] = "Calculus (" + CharacterMoves.CalculusCost + " mana)"; Game.ActionOne [0] = Game.CharacterOne + " attacks " + Game.CharacterTwo + "."; Game.ActionOne [1] = "Cody is very calm in every situation."; Game.ActionOne [2] = "Cody jumps up and kicks " + Game.CharacterTwo + " in the face."; Game.ActionOne [3] = "Cody facepalms at " + Game.CharacterTwo + "."; Game.ActionOne [4] = "Cody uses the powers of calculus against " + Game.CharacterTwo + "."; } else if (Game.characterChoice == 2) { Game.CharacterTwo = "Cody"; Game.CharacterTwoHP = CharacterStats.CodyHP; Game.CharacterTwoAttack = CharacterStats.CodyAttack; Game.CharacterTwoMana = CharacterStats.CodyMana; Game.CharacterTwoRegen = CharacterStats.CodyRegen; Game.MovesTwo = CharacterMoves.CodyMoves; Game.MoveTwoValue [0] = CharacterStats.CodyAttack; Game.MoveTwoValue [1] = CharacterMoves.Calm; Game.MoveTwoValue [2] = CharacterMoves.FlyingKick; Game.MoveTwoValue [3] = CharacterMoves.FacePalm; Game.MoveTwoValue [4] = CharacterMoves.Calculus; Game.MoveTwoCost [0] = CharacterMoves.AttackCost; Game.MoveTwoCost [1] = CharacterMoves.CalmCost; Game.MoveTwoCost [2] = CharacterMoves.FlyingKickCost; Game.MoveTwoCost [3] = CharacterMoves.FacePalmCost; Game.MoveTwoCost [4] = CharacterMoves.CalculusCost; Game.OptionsTwo [0] = "Attack (" + CharacterMoves.AttackCost + " mana)"; Game.OptionsTwo [1] = "Calm (" + CharacterMoves.CalmCost + " mana)"; Game.OptionsTwo [2] = "FlyingKick (" + CharacterMoves.FlyingKickCost + " mana)"; Game.OptionsTwo [3] = "FacePalm (" + CharacterMoves.FacePalmCost + " mana)"; Game.OptionsTwo [4] = "Calculus (" + CharacterMoves.CalculusCost + " mana)"; Game.ActionTwo [0] = Game.CharacterTwo + " attacks " + Game.CharacterOne + "."; Game.ActionTwo [1] = "Cody is very calm in every situation."; Game.ActionTwo [2] = "Cody jumps up and kicks " + Game.CharacterOne + " in the face."; Game.ActionTwo [3] = "Cody facepalms at " + Game.CharacterOne + "."; Game.ActionTwo [4] = "Cody uses the powers of calculus against " + Game.CharacterOne + "."; } }
2
public void load45DegreeSlope(Rectangle2D e) { for(int x = 0; x < TileSet.tileWidth; x++) { platforms.add(new Platform(new Rectangle2D.Double(e.getX() + x, e.getY() + x, 1f, 2f))); } }
1
public Transition modifyTransition(Transition transition, TableModel model) { TMTransition t = (TMTransition) transition; try { String[] reads = new String[machine.tapes()]; String[] writes = new String[machine.tapes()]; String[] dirs = new String[machine.tapes()]; for (int i = 0; i < machine.tapes(); i++) { reads[i] = (String) model.getValueAt(i, 0); writes[i] = (String) model.getValueAt(i, 1); dirs[i] = (String) model.getValueAt(i, 2); } TMTransition newTrans = new TMTransition(t.getFromState(), t .getToState(), reads, writes, dirs); if (transition instanceof TMTransition) { TMTransition oldTrans = (TMTransition) transition; newTrans.setBlockTransition(oldTrans.isBlockTransition()); } return newTrans; } catch (IllegalArgumentException e) { reportException(e); return null; } }
3
@Override public void initWithMessage(String messageString) { Matcher matcher = PATTERN.matcher(messageString); if (matcher.matches()) { if (!matcher.group(1).equals("null")) { this.setplayerPositionID1(Integer.parseInt(matcher.group(1))); } if (!matcher.group(2).equals("null")) { this.setplayerPositionID2(Integer.parseInt(matcher.group(2))); } if (!matcher.group(3).equals("null")) { this.setplayerPositionID3(Integer.parseInt(matcher.group(3))); } if (!matcher.group(4).equals("null")) { this.setplayerPositionID4(Integer.parseInt(matcher.group(4))); } if (!matcher.group(5).equals("null")) { this.setpPlayer1(Integer.parseInt(matcher.group(5))); } if (!matcher.group(6).equals("null")) { this.setpPlayer2(Integer.parseInt(matcher.group(6))); } if (!matcher.group(7).equals("null")) { this.setpPlayer3(Integer.parseInt(matcher.group(7))); } if (!matcher.group(8).equals("null")) { this.setpPlayer4(Integer.parseInt(matcher.group(8))); } } }
9
public void AtualizarProjeto(Projeto projeto) throws SQLException { Connection conexao = null; PreparedStatement comando = null; try { conexao = BancoDadosUtil.getConnection(); comando = conexao.prepareStatement(SQL_UPDATE_UM_PROJETO); comando.setString(1, projeto.getNome()); comando.setString(2, projeto.getDescricao()); comando.setDate(3, (Date) projeto.getDataInicio()); comando.setDate(4, (Date) projeto.getDataTermino()); comando.setString(5, projeto.getDepartamento().getCodigo()); comando.setInt(6, projeto.getIdProjeto()); comando.executeUpdate(); 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(); } } }
6
public Constant newMethod(final String owner, final String name, final String desc, final boolean itf) { key3.set(itf ? 'N' : 'M', owner, name, desc); Constant result = get(key3); if (result == null) { newClass(owner); newNameType(name, desc); result = new Constant(key3); put(result); } return result; }
2
private void initRat() { Reflections reflections = new Reflections("de.LittleRolf.MazeOverkill"); Set<Class<? extends MazeRat>> subTypes = reflections .getSubTypesOf(MazeRat.class); for (Class<? extends MazeRat> clazz : subTypes) { try { rats.add(clazz.getConstructor(Point.class, Maze.class) .newInstance(startPoint.clone(), this)); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
9
private static String toSimpleCase(String value, boolean upper) { if (value == null || value.length() == 0) { return value; } char[] ca = value.toCharArray(); for (int i = 0; i < ca.length; i++) { int type = getType(ca[i]); if (upper && type == LOWER) { ca[i] = (char)(ca[i] - 32); } else if (!upper && type == UPPER) { ca[i] = (char)(ca[i] + 32); } } return String.valueOf(ca); }
7
public double[] train(List<Instance> trainingInstances, List<Instance> testingInstances) { int dimension = trainingInstances.get(0).getFeatures().length; int trainSize= trainingInstances.size(); int testSize = testingInstances.size(); List<double[]> weights = new ArrayList<double[]>(); List<Integer> c = new ArrayList<Integer>(); // c is w's survival time int epoches = 0; int n = 0; // No. of update double[] weight = new double[dimension]; int counter = 0; weights.add(weight); c.add(0); while(epoches < 100){ int errorNum = 0; Collections.shuffle(trainingInstances); for(int m = 0; m < trainSize; m++){ Instance instance = trainingInstances.get(m); double[] currentWeight = weights.get(n); double[] feature = instance.getFeatures(); double u = DoubleOperation.multiply(feature, currentWeight); double label = instance.getLabel(); if((label*u) <= 0){ double[] change = DoubleOperation.multiply(feature, label); double[] newWeight = DoubleOperation.plus(currentWeight, change); weights.add(newWeight); n++; c.add(counter); counter = 1; } else { counter += 1; } } for(int i = 0; i < testSize; i++){ Instance instance = testingInstances.get(i); double[] feature = instance.getFeatures(); double label = instance.getLabel(); double value = 0.0; for(int j = 0; j < weights.size(); j++){ assert weights.size() == c.size(); double wx = DoubleOperation.multiply(feature, weights.get(j)); value += c.get(j)*sign(wx); } double predicateLabel = sign(value); if (predicateLabel != label) { errorNum += 1; } } epoches++; System.out.println("Epoch: "+epoches+" Error's count is " + errorNum); } for(int i = 0; i < testSize; i++){ Instance instance = trainingInstances.get(i); double[] feature = instance.getFeatures(); double label = instance.getLabel(); double wx = DoubleOperation.multiply(feature, weights.get(n)); double predictLabel = sign(wx); String features = IOUtils.toStringFromI(feature, 1); String testInfo = predictLabel + " " + features; // IOUtils.writeToFile("Voted_test.txt", testInfo); } return weights.get(n); }
7
@EventHandler public void CaveSpiderBlindness(EntityDamageByEntityEvent event) { Entity e = event.getEntity(); Entity damager = event.getDamager(); String world = e.getWorld().getName(); boolean dodged = false; Random random = new Random(); double randomChance = plugin.getCaveSpiderConfig().getDouble("CaveSpider.Blindness.DodgeChance") / 100; final double ChanceOfHappening = random.nextDouble(); if (ChanceOfHappening >= randomChance) { dodged = true; } if ( plugin.getCaveSpiderConfig().getBoolean("CaveSpider.Blindness.Enabled", true) && damager instanceof CaveSpider && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) { Player player = (Player) e; player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, plugin.getCaveSpiderConfig().getInt("CaveSpider.Blindness.Time"), plugin.getCaveSpiderConfig().getInt("CaveSpider.Blindness.Power"))); } }
6
private void jPanel1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPanel1MouseClicked String message = jTextArea1.getText().replace("\n", ""); //sending message try { String selected = this.getjList1().getSelectedValue().toString().trim(); ChatClientConnection chatClient = null; String id = null; for(User onlineUser: onlineUsers) { id = onlineUser.getId(); if(id.trim().equals(selected)) { try { new ChatClientConnection(onlineUser.getIp(), onlineUser.getUDPServerPort()).sendChatMessage(message); } catch (Exception ex) { Logger.getLogger(MainContent.class.getName()).log(Level.SEVERE, null, ex); } break; } } chat.getjTextArea1().append("\nME: " + message); jTextArea1.setText("\n"); } catch(NullPointerException e) { new ErrorPanel(" User must be selected \n before sending message!").display(); } }//GEN-LAST:event_jPanel1MouseClicked
4
public void doRun(int run) throws Exception { if (m_ResultProducer == null) { throw new Exception("No ResultProducer set"); } if (m_ResultListener == null) { throw new Exception("No ResultListener set"); } if (m_Instances == null) { throw new Exception("No Instances set"); } // Randomize on a copy of the original dataset Instances runInstances = new Instances(m_Instances); runInstances.randomize(new Random(run)); /*if (runInstances.classAttribute().isNominal() && (m_Instances.numInstances() / m_StepSize >= 1)) { // runInstances.stratify(m_Instances.numInstances() / m_StepSize); }*/ // Tell the resultproducer to send results to us m_ResultProducer.setResultListener(this); // For each subsample size if (m_LowerSize == 0) { m_CurrentSize = m_StepSize; } else { m_CurrentSize = m_LowerSize; } while (m_CurrentSize <= m_Instances.numInstances() && ((m_UpperSize == -1) || (m_CurrentSize <= m_UpperSize))) { m_ResultProducer.setInstances(new Instances(runInstances, 0, m_CurrentSize)); m_ResultProducer.doRun(run); m_CurrentSize += m_StepSize; } }
7
private ArrayList<Move> getAttackingMoves(ArrayList<Move> allMoves) { // TODO Auto-generated method stub ArrayList<Move> answer = new ArrayList<Move>(allMoves.size()); for(Move m : allMoves) { Piece pieceBeingAttacked=myGame.getPiece(m.getCurrentLocation()); if(pieceBeingAttacked!=null&&pieceBeingAttacked.isWhite!=this.myColor|| isPawnAttack(m)) { answer.add(m); } } return answer; }
4
public Socket getSocket() { return _socket; }
0
public static void update() { for (int i = 0; i < NUM_KEYCODES; i++) lastKeys[i] = getKey(i); for (int i = 0; i < NUM_MOUSEBUTTONS; i++) lastMouse[i] = getMouse(i); }
2
public static void main(String args[]) throws Exception { ExecutorService pool = Executors.newFixedThreadPool(4); Set<Future<Integer>> set = new HashSet<Future<Integer>>(); String[] args1 = "13 12 12 14".split(" "); for (String word: args1) { Callable<Integer> callable = new WordLengthCallable(word); Future<Integer> future = pool.submit(callable); set.add(future); } int sum = 0; for (Future<Integer> future : set) { sum += future.get(); } System.out.printf("The sum of lengths is %s%n", sum); System.exit(sum); }
2
private ArrayList<String> fetchMatchingAnstallda() { String searchFor = tfAnstalldSearch.getText(); ArrayList<HashMap<String, String>> temp = null; try { temp = DB.fetchRows("select * from anstalld"); } catch (InfException e) { e.getMessage(); } ArrayList<String> res = new ArrayList<>(); for (HashMap<String, String> hmt : temp) { for (String st : hmt.values()) { if (st != null && st.toLowerCase().contains(searchFor.toLowerCase())) { res.add(hmt.get("AID")); } } } // run results through a Set to remove duplicates HashSet hs = new HashSet(res); res.clear(); res.addAll(hs); return res; }
5
private String useTextBoxVariables(String s) { int n = view.getNumberOfInstances(TextBoxComponent.class); if (n <= 0) return s; int lb = s.indexOf("%textbox["); int rb = s.indexOf("].", lb); int lb0 = -1; String v; int i; TextBoxComponent text; while (lb != -1 && rb != -1) { v = s.substring(lb + 9, rb); double x = parseMathExpression(v); if (Double.isNaN(x)) break; i = (int) Math.round(x); if (i < 0 || i >= n) { out(ScriptEvent.FAILED, "Text box " + i + " does not exist."); break; } v = escapeMetaCharacters(v); text = view.getTextBox(i); s = replaceAll(s, "%textbox\\[" + v + "\\]\\.x", text.getRx() * R_CONVERTER); s = replaceAll(s, "%textbox\\[" + v + "\\]\\.y", text.getRy() * R_CONVERTER); s = replaceAll(s, "%textbox\\[" + v + "\\]\\.width", text.getWidth() * R_CONVERTER); s = replaceAll(s, "%textbox\\[" + v + "\\]\\.height", text.getHeight() * R_CONVERTER); s = replaceAll(s, "%textbox\\[" + v + "\\]\\.angle", text.getAngle()); lb0 = lb; lb = s.indexOf("%textbox["); if (lb0 == lb) // infinite loop break; rb = s.indexOf("].", lb); } return s; }
7
public AngleDR Mapqk(Stardata s, AMParams amprms) { int i; double pmt, gr2e, ab1, eb[], ehn[], abv[], q[], pxr, w, em[] = new double[3], p[] = new double[3], pn[] = new double[3], pde, pdep1, p1[] = new double[3], p1dv, p2[] = new double[3], p3[] = new double[3]; TRACE("Mapqk"); /* Unpack scalar and vector parameters */ pmt = amprms.getTimeint(); gr2e = amprms.getGrad(); ab1 = amprms.getRoot(); eb = amprms.getBary(); ehn = amprms.getHelio(); abv = amprms.getEarthv(); /* Spherical to x,y,z */ AngleDR r = s.getAngle(); double rm = r.getAlpha(); double dm = r.getDelta(); double pm[] = s.getMotion(); double px = s.getParallax(); double rv = s.getRV(); q = Dcs2c(r); /* Space motion (radians per year) */ pxr = px * DAS2R; w = VF * rv * pxr; em[0] = (-pm[0] * q[1]) - (pm[1] * Math.cos(rm) * Math.sin(dm)) + (w * q[0]); em[1] = (pm[0] * q[0]) - (pm[1] * Math.sin(rm) * Math.sin(dm)) + (w * q[1]); em[2] = (pm[1] * Math.cos(dm)) + (w * q[2]); /* Geocentric direction of star (normalized) */ for (i = 0; i < 3; i++) { p[i] = q[i] + (pmt * em[i]) - (pxr * eb[i]); } w = Dvn(p, pn); /* Light deflection (restrained within the Sun's disc) */ pde = Dvdv(pn, ehn); pdep1 = 1.0 + pde; w = gr2e / gmax(pdep1, 1.0e-5); for (i = 0; i < 3; i++) { p1[i] = pn[i] + (w * (ehn[i] - pde * pn[i])); } /* Aberration (normalization omitted) */ p1dv = Dvdv(p1, abv); w = 1.0 + p1dv / (ab1 + 1.0); for (i = 0; i < 3; i++) { p2[i] = ab1 * p1[i] + w * abv[i]; } /* Precession and nutation */ p3 = Dmxv(amprms.getPrecess(), p2); /* Geocentric apparent RA,dec */ AngleDR ra = Dcc2s(p3); ra.setAlpha(Dranrm(ra.getAlpha())); ENDTRACE("Mapqk"); return ra; }
3
public List<ExtensionsType> getExtensions() { if (extensions == null) { extensions = new ArrayList<ExtensionsType>(); } return this.extensions; }
1
public void cleanFactory() { List<M> models = new ArrayList<M>(this.models); for (M model : models) if (model.getModelId().isNewId() && model.getModelStatus() == ModelStatus.TO_DELETE) this.markDeleted(model); for (M model : models) if (model.getModelStatus() == ModelStatus.DELETED) this.unregister(model); }
5
public String toString(){ StringBuffer sb = new StringBuffer(); switch(type){ case TYPE_VALUE: sb.append("VALUE(").append(value).append(")"); break; case TYPE_LEFT_BRACE: sb.append("LEFT BRACE({)"); break; case TYPE_RIGHT_BRACE: sb.append("RIGHT BRACE(})"); break; case TYPE_LEFT_SQUARE: sb.append("LEFT SQUARE([)"); break; case TYPE_RIGHT_SQUARE: sb.append("RIGHT SQUARE(])"); break; case TYPE_COMMA: sb.append("COMMA(,)"); break; case TYPE_COLON: sb.append("COLON(:)"); break; case TYPE_EOF: sb.append("END OF FILE"); break; } return sb.toString(); }
8
private void inicializarNivel(String nivelIngresado){ if(nivelIngresado.equals("Basico")){ nivel = nivel + nivelIngresado; intentos = 6; pistasPermitidas = 3; } if(nivelIngresado.equals("Intermedio")){ nivel = nivel + "Intermedio"; intentos = 4; pistasPermitidas = 2; } if(nivelIngresado.equals("Avanzado")){ nivel = nivel + "Avanzado"; intentos = 2; pistasPermitidas = 1; } }
3
public Robot createRobotInstance(final ClassInfo info) throws IOException, ReflectiveOperationException { final PluginClassLoader loader = new PluginClassLoader(ClassLoader.getSystemClassLoader()); final ClassOrigin origin = info.getOrigin(); if(origin.inJar) { loader.defineJar(info); } else { Set<ClassInfo> depends = PluginService.getDependancies(info); for(ClassInfo dep : depends) { loader.defineClass(dep); } } loader.whitelist("roboflight.**"); loader.whitelist("java.awt.Color"); loader.whitelist("java.awt.Point"); loader.whitelist("java.awt.Rectangle"); loader.whitelist("java.awt.geom.**"); loader.whitelist("java.io.**"); loader.blacklist("java.io.Console"); loader.blacklist("java.io.File"); loader.blacklist("java.io.FileDescriptor"); loader.blacklist("java.io.FileInputStream"); loader.blacklist("java.io.FileOutputStream"); loader.blacklist("java.io.FilePermission"); loader.blacklist("java.io.FileReader"); loader.blacklist("java.io.FileWriter"); loader.blacklist("java.io.RandomAccessFile"); loader.whitelist("java.lang.**"); loader.blacklist("java.lang.SecurityManager"); loader.blacklist("java.lang.Thread"); loader.blacklist("java.lang.ThreadGroup"); loader.blacklist("java.lang.ThreadLocal"); loader.blacklist("java.lang.Runtime"); loader.blacklist("java.lang.RuntimePermission"); loader.blacklist("java.lang.ProcessBuilder"); loader.blacklist("java.lang.Process"); loader.blacklist("java.lang.System"); loader.blacklist("java.lang.InheritableThreadLocal"); loader.blacklist("java.lang.instrument.**"); loader.blacklist("java.lang.invoke.**"); loader.blacklist("java.lang.management.**"); loader.blacklist("java.lang.ref.**"); loader.blacklist("java.lang.reflect.**"); loader.whitelist("java.math.**"); loader.whitelist("java.util.**"); loader.whitelist("java.util.concurrent.**"); loader.blacklist("java.util.jar.**"); loader.blacklist("java.util.logging.**"); loader.blacklist("java.util.prefs.**"); loader.blacklist("java.util.spi.**"); loader.blacklist("java.util.zip.**"); Class<?> robot = loader.loadClass(info.toString()); return (Robot) robot.newInstance(); }
3
public CropState state() { if (this instanceof IWeeds) { if (((IWeeds) this).weeds() > 0) { return CropState.WEEDS; } } if (empty()) { return CropState.EMPTY; } if (this instanceof ICanDie) { ICanDie canDie = (ICanDie) this; if (canDie.diseased()) { return CropState.DISEASED; } if (canDie.dead()) { return CropState.DEAD; } } if (grown()) { return CropState.READY; } if (this instanceof ICanWater) { if (((ICanWater) this).watered()) { return CropState.WATERED; } } return CropState.GROWING; }
9
public CheckResultMessage check21(int day) { int r = get(39, 5); int c = get(40, 5); BigDecimal b = new BigDecimal(0); if (checkVersion(file).equals("2003")) { try { in = new FileInputStream(file); hWorkbook = new HSSFWorkbook(in); b = getValue(r + 1, c + day, 10).subtract( getValue(r, c + day, 10)); if (0 != getValue(r + 2, c + day, 10).compareTo(b)) { return error("支付机构汇总报表<" + fileName + ">客户资金余额变动额 :" + day + "日错误"); } } catch (Exception e) { } } else { try { in = new FileInputStream(file); hWorkbook = new HSSFWorkbook(in); b = getValue1(r + 1, c + day, 10).subtract( getValue1(r, c + day, 10)); if (0 != getValue1(r + 2, c + day, 10).compareTo(b)) { return error("支付机构汇总报表<" + fileName + ">客户资金余额变动额 :" + day + "日错误"); } } catch (Exception e) { } } return pass("支付机构汇总报表<" + fileName + ">客户资金余额变动额 :" + day + "日正确"); }
5
public boolean canPlaceRobber(HexLocation hexLoc) { if(hexLoc.equals(serverModel.getMap().getRobber().getLocation()) || gameModel.getBoard().get(hexLoc).getType() == HexType.WATER) return false; return true; }
2
public static void streamCopy(InputStream is, OutputStream os) throws IOException { byte[] buffer = new byte[1024 * 1024]; int bytesRead; while ((bytesRead = is.read(buffer)) > 0) { os.write(buffer, 0, bytesRead); } }
1
@SuppressWarnings({ "rawtypes", "unchecked" }) public JList getFontStyleList() { if (fontStyleList == null) { fontStyleList = new JList(getFontStyleNames()); fontStyleList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); fontStyleList.addListSelectionListener( new ListSelectionHandler(getFontStyleTextField())); fontStyleList.setSelectedIndex(0); fontStyleList.setFont(DEFAULT_FONT); fontStyleList.setFocusable(false); } return fontStyleList; }
1
public static double similarity(int userId1, int userId2, MoviesAndRatings mar1, MoviesAndRatings mar2) throws SQLException { double result = 0; List<Movie> list1 = mar1.getMovies(); List<Movie> list2 = mar2.getMovies(); if (movies == null) movies = getMovies(); List<Movie> commonMovies = new LinkedList<Movie>(); for (Movie m1 : list1) { for (Movie m2 : list2) { if (m1.getMovieId() == m2.getMovieId()) commonMovies.add(m1); } } double s1 = 0; double s2 = 0; double s3 = 0; for (Movie movie : commonMovies) { double v1 = getVoteOfUserForItem(userId1, movie.getMovieId(), mar1); double v2 = getVoteOfUserForItem(userId2, movie.getMovieId(), mar2); s1 += v1 * v2; for (Movie m1 : list1) { s2 += Math .pow(getVoteOfUserForItem(userId1, m1.getMovieId(), mar1), 2); } for (Movie m2 : list2) { s3 += Math .pow(getVoteOfUserForItem(userId2, m2.getMovieId(), mar2), 2); } } result = s1 / (Math.sqrt(s1) * Math.sqrt(s2)); return result; }
7
@Override public int getValues(AnimatedScore target, int tweenType, float[] returnValues) { switch(tweenType) { case ALPHA: returnValues[0] = target.getColor().a; return 1; default: assert false; return -1; } }
1
private void actuallyLoad() { if (this.current < 0) return; if (this.current == this.loader.getIndex()) { // We are in the process of pre-fetching the image we want to // display. if (this.loader.isLoaded()) { this.onLoaded(this.loader.getImageElement()); return; } else if (!this.loader.isCanceled ()) { this.loader.setShowOnLoad(true); return; } } if (this.loader.isLoading()) { this.loader.cancel(); } PictureDescriptor desc = this.descriptors.get(this.current); if (desc.isPicture()) { if (this.video != null) { this.remove(this.video); this.video = null; this.imgPlay.setDisabled(false); } this.loader.load(this.current, true); } else { this.loader.index = this.current; this.loader.state = InternalLoader.ERROR; this.old = this.img; this.img = null; if (this.old != null) { this.fadeAnim = new Animation() { @Override protected void onUpdate(double progress) { PictureView.this.drawCanvas(progress); if (progress == 1) { PictureView.this.old = null; PictureView.this.fadeAnim = null; PictureView.this.showVideo(); } } }; this.fadeAnim.run(800); } else { this.showVideo(); } } }
9
@Test public void findDuplicateTypeHand_whenThreeFoursTwoJacksTwoKingsExist_returnsFullHouseFoursOverKings() { Hand hand = findDuplicateTypeHand(foursFullWithTwoJacksAndTwoKings()); assertEquals(HandRank.FullHouse, hand.handRank); assertEquals(Rank.Four, hand.ranks.get(0)); assertEquals(Rank.King, hand.ranks.get(1)); }
0
public void giveBump(Entity e){ char bumpIdentity = e.getIdentity(); if (bumpIdentity == analagousStates[0]){ decisions.analagousGas(e); } if (bumpIdentity == analagousStates[1]){ decisions.analagousLiquid(e); } if (bumpIdentity == analagousStates[2]){ decisions.analagousSolid(e); } if (bumpIdentity == weakerStates[0]){ decisions.weakerGas(e); } if (bumpIdentity == weakerStates[1]){ decisions.weakerLiquid(e); } if (bumpIdentity == weakerStates[2]){ decisions.weakerSolid(e); } if (bumpIdentity == strongerStates[0]){ decisions.strongerGas(e); } if (bumpIdentity == strongerStates[1]){ decisions.strongerLiquid(e); } if (bumpIdentity == strongerStates[2]){ decisions.strongerSolid(e); } }
9
public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D)g; g2.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.drawImage(new ImageIcon(Utils.getLocalImage("/images/news_bg.png",this)).getImage(), 0, 0, null); Font font=null; Font font2=null; try { font = Font.createFont(Font.TRUETYPE_FONT, this.getClass().getResourceAsStream("/font/Nautilus.ttf")); font2 = Font.createFont(Font.TRUETYPE_FONT, this.getClass().getResourceAsStream("/font/LucidaSansRegular.ttf")); } catch (FontFormatException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } if(titles!=null&&titles.length!=0){ int size = titles.length; int k=50; font = font.deriveFont(20.0f); font2 = font2.deriveFont(14.0f); size = (size>3) ? 3 : size; for(int i=0;i<size;i++){ g2.setFont(font); g2.setColor(Color.decode("#434343")); g2.drawString(titles[i],30,k); g2.setFont(font2); g2.setColor(Color.decode("#606060")); g2.drawString(descriptions[i],40,k+20); k+=70; } } }
6
CompilerGUI() { super("Compiler");//标题 setLayout(null);//布局 setBackground(Color.gray);//背景色 setSize(1240, 700);// setVisible(true);//设置可见 load = new Button("Load File");//创建按钮 ge_token = new Button("GE Token"); ge_tree = new Button("GE Tree"); ge_llvm = new Button("GE LLVM"); quit = new Button("Exit"); tarea = new TextArea("");//创建文本框 tareaout = new TextArea(""); tarea.setFont(new Font("SansSerif",Font.BOLD,15)); tareaout.setFont(new Font("SansSerif",Font.BOLD,15)); add(load);//添加按钮 add(ge_token); add(ge_tree); add(ge_llvm); add(quit); add(tarea); add(tareaout); tarea.setBounds(30, 50, 440, 600);//设置文本框位置 tareaout.setBounds(600,50,600,600); load.setBounds(500, 60, 70, 30); ge_token.setBounds(500, 120, 70, 30); ge_tree.setBounds(500, 180, 70, 30); ge_llvm.setBounds(500, 240, 70, 30); quit.setBounds(500,300,70,30); open = new FileDialog(this, "打开", FileDialog.LOAD);//新建对话框 //sv = new FileDialog(this, "保存", FileDialog.SAVE); open.setFilenameFilter(new FilenameFilter() { @Override public boolean accept(File dir, String name) { if(name.endsWith(".ml")) return true; return false; } }); load.addActionListener(this);//设置按钮点击监听事件 ge_token.addActionListener(this); ge_tree.addActionListener(this); ge_llvm.addActionListener(this); quit.addActionListener(this); addWindowListener(new WindowAdapter() {//关闭事件处理 public void windowClosing(WindowEvent e) { setVisible(false);//设置不可见 System.exit(0);//程序关闭 } }); }
1
private Exam parseExam(final Node exam) { String name = ""; String mark = ""; final NodeList fields = exam.getChildNodes(); for (int i = 0; i < fields.getLength(); ++i) { final Node field = fields.item(i); if (field != null) { if (field.getNodeType() == Node.ELEMENT_NODE) { final Node item = field.getChildNodes().item(0); if (item != null) { if (field.getNodeName() == Model.FIELD_NAME) { name = item.getNodeValue(); } if (field.getNodeName() == Model.FIELD_MARK) { mark = item.getNodeValue(); } } } } } return new Exam(name, Util.isNumeric(mark) ? Integer.parseInt(mark) : null); }
7
@Override public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) { if (msg instanceof HttpResponse) { HttpResponse response = (HttpResponse) msg; System.err.println("STATUS: " + response.getStatus()); System.err.println("VERSION: " + response.getProtocolVersion()); if (!response.headers().isEmpty()) { for (String name : response.headers().names()) { for (String value : response.headers().getAll(name)) { System.err.println("HEADER: " + name + " = " + value); } } } if (response.getStatus().code() == 200 && response.headers().contains(HttpHeaders.Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED, true)) { readingChunks = true; System.err.println("CHUNKED CONTENT {"); } else { System.err.println("CONTENT {"); } } if (msg instanceof HttpContent) { HttpContent chunk = (HttpContent) msg; System.err.println(chunk.content().toString(CharsetUtil.UTF_8)); if (chunk instanceof LastHttpContent) { if (readingChunks) { System.err.println("} END OF CHUNKED CONTENT"); } else { System.err.println("} END OF CONTENT"); } readingChunks = false; } else { System.err.println(chunk.content().toString(CharsetUtil.UTF_8)); } } }
9
private JButton getBtnGetLyrics() { if (btnGetLyrics == null) { btnGetLyrics = new JButton("Get lyrics"); btnGetLyrics.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { WikiaXMLHandler xmlHandler = new WikiaXMLHandler(); SongFinder songFinder = new SongFinder(); String artistName = txFieldArtistName.getText(); String songName = txFieldSongName.getText(); String[] urlAndLyrics = xmlHandler.getUriAndLyricsSnippet(artistName, songName); if(urlAndLyrics!=null){ String lyrics = songFinder.findAndExtractSong(urlAndLyrics[0],urlAndLyrics[1]); textAreaMain.append(lyrics+"\n"); } else textAreaMain.append("Cant find songs lyrics, mabey Song or artist name are not right...\n"); } }); btnGetLyrics.setBounds(124, 222, 89, 23); } return btnGetLyrics; }
2
public void actionPerformed(ActionEvent e) { if(e.getActionCommand().equals(add.getActionCommand())){ PositionTransformation pt = parent.getTransformator(); if(pt.supportReverseTranslation()) { pt.translateToLogicPosition(pos.x, pos.y); parent.addSingleNode(new Position(pt.logicX, pt.logicY, pt.logicZ)); } } }
2
private void handleRegionRect(Attributes atts) { if (currentRects == null) return; int i, l=0, t=0, r=0, b=0; if ((i = atts.getIndex(ATTR_l)) >= 0) { l = new Integer(atts.getValue(i)); } if ((i = atts.getIndex(ATTR_t)) >= 0) { t = new Integer(atts.getValue(i)); } if ((i = atts.getIndex(ATTR_r)) >= 0) { r = new Integer(atts.getValue(i)); } if ((i = atts.getIndex(ATTR_b)) >= 0) { b = new Integer(atts.getValue(i)); } currentRects.add(new Rect(l, t, r, b)); }
5
private boolean memeChecker(String input) { boolean isAMeme = false; for (String currentMeme : memeList) { if (input.equalsIgnoreCase(currentMeme)) { isAMeme = true; } } return isAMeme; }
2
private void initPathField(){ /* * Initialize text field to form which sets the path to dictionaries; */ directoryPath = new JTextField(destinationDir.getAbsolutePath()); directoryPath.setSize(FP_TFIELD_SIZE); directoryPath.setLocation(5, 10); /* * Initialize button which lets to choose the path to dictionary; */ ImageIcon iconOpenPath = new ImageIcon(Main.icoPath + "folder.png"); JButton openPath = new JButton(iconOpenPath); openPath.setSize(F_OPEN_SIZE); openPath.setLocation(directoryPath.getX()+directoryPath.getWidth()+5, directoryPath.getY()); openPath.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { showDirOpenDialog(); } }); add(directoryPath); add(openPath); }
0
public Leaf(Link key, int t, Junction parent, Leaf next, Leaf previous){ this.T= t; this.size= 1; this.data= new Vector<Link>(); this.next= next; this.parent= parent; if ((previous != null) && (next != null)){ //sets the new Link's 'next' and 'prev' values this.data.add(key); key.setNext(next.getFirst()); key.setPrev(previous.getLast()); previous.setNext(this); } else if ((previous == null) && (next != null)){ this.data.add(key); key.setNext(next.getFirst()); key.setPrev(null); } else if ((previous != null) && (next == null)){ this.data.add(key); key.setNext(null); key.setPrev(previous.getLast()); previous.setNext(this); } else { this.data.add(key); key.setNext(null); key.setPrev(null); } }//Leaf(Link, int, Junction, Leaf, Leaf)
6
public int findPath(int beginning, int target, Oergi oergi) { this.path = new ArrayList<Integer>(); this.oergi = oergi; prioritizeVortexes(beginning); while (!vortexHeap.isEmpty()) { Vortex closestVortex = vortexHeap.remove(); if (closestVortex.getId() == target) { backtrackPath(closestVortex); return closestVortex.getDayDistance() + 1; } ArrayList<Integer> neighbors = closestVortex.getNeighbors(); ArrayList<Integer> paths = closestVortex.getPaths(); for (int i=0; i<neighbors.size(); i++) { relax(closestVortex, paths.get(i), neighbors.get(i)); } } return -1; }
3
private static void afficherEtudiantCours() { ArrayList<Cours> listeCours = ListeCours.getInstance().getListe(); // Liste des cours int i = 0; // Compteur int element; // Nombre lu au clavier representant le numero d'un cours Cours choix = null; // Cours dont on veut afficher les etudiants String choixCours; // Chaine de caractere lue au clavier representant un numero de cours for (Cours cours : listeCours) { if (i % 3 == 0) System.out.println((i+1) + ". " + cours.getSigle() + "\t"); else System.out.println((i+1) + ". " + cours.getSigle()); i++; } if (i > 1) { do { System.out.println("Choisissez le cours dont vous voulez afficher les etudiants : "); choixCours = Interface.lecture(); element = isNumeric(choixCours) ? Integer.parseInt(choixCours) : -1; if(element > 0 && element <= i) choix = listeCours.get(element-1); } while( (element < 1 || element > i)); if (choix.getPremierEtudiant() != null) { System.out.println("\nListe des etudiants du cours " + choix.getNom()); System.out.println("================================================"); afficherEtudiant(choix.getPremierEtudiant()); } else System.out.println("Il n'y a aucun etudiant inscrit au cours choisit!"); } else System.out.println("Il n'y a pas de cours"); lecture(); menuPrincipal(); // Affichage du menu principal }
9
public synchronized static AlienFXController getAlienFXDevice() throws AlienFXControllerNotFoundException, AlienFXControllerUnknownDeviceException, AlienFXCommunicationException { if(controller != null) return controller; int deviceId = LEDController.initialize(); if(deviceId == LEDController.NOT_FOUND) throw new AlienFXControllerNotFoundException(); else if (deviceId == LEDController.ALLPOWERFULL_ALIENFX) controller = new AlienFXAllPowerFull(); else if(deviceId == LEDController.AREA51_ALIENFX) controller = new AlienFXArea51Controller(); else if(deviceId == LEDController.M14XR2_ALIENFX) controller = new AlienFXM14xR2Controller(); else if(deviceId == LEDController.M14XR3_ALIENFX) controller = new AlienFXM14xR3Controller(); else if(deviceId == LEDController.M17XR3_ALIENFX) controller = new AlienFXM17xController("Alienware M17x R3"); else if(deviceId == LEDController.M17X_ALIENFX) controller = new AlienFXM17xController(); else if(deviceId == LEDController.M18XR2_ALIENFX) controller = new AlienFXM18xR2Controller(); else throw new AlienFXControllerUnknownDeviceException(); controller.ping(); return controller; }
9
public static boolean shouldBuild() { int bays = UnitCounter.getNumberOfUnits(buildingType); // int barracks = // UnitCounter.getNumberOfUnits(TerranBarracks.getBuildingType()); int factories = UnitCounter.getNumberOfUnits(TerranFactory.getBuildingType()); // // Version for expansion with cannons // if (BotStrategyManager.isExpandWithBunkers()) { // if (bays == 0 && xvr.canAfford(132) && // !Constructing.weAreBuilding(buildingType)) { // // if (UnitCounter.getNumberOfBattleUnits() >= 15) { // ShouldBuildCache.cacheShouldBuildInfo(buildingType, true); // return true; // // } // } // } // Version for expansion with gateways if (BotStrategyManager.isExpandWithBarracks()) { if (bays == 0 && factories >= 2 && !Constructing.weAreBuilding(buildingType)) { if (UnitCounter.getNumberOfBattleUnits() >= 14) { return ShouldBuildCache.cacheShouldBuildInfo(buildingType, true); } } } // if (bays == 1 && // UnitCounter.getNumberOfUnits(TerranBarracks.getBuildingType()) >= 4 // && xvr.canAfford(650) && !Constructing.weAreBuilding(buildingType)) { // if (UnitCounter.getNumberOfBattleUnits() >= 18) { // ShouldBuildCache.cacheShouldBuildInfo(buildingType, true); // return true; // } // } // // if (bays == 2 && xvr.canAfford(900) && // !Constructing.weAreBuilding(buildingType)) { // ShouldBuildCache.cacheShouldBuildInfo(buildingType, true); // return true; // } return ShouldBuildCache.cacheShouldBuildInfo(buildingType, false); }
5
private static void checkName(String label, String ident) { if (ident.length() == 0) { throw new EdnSyntaxException("The " + label + " must not be empty."); } char first = ident.charAt(0); if (isDigit(first)) { throw new EdnSyntaxException("The " + label + " '" + ident + "' must not begin with a digit."); } if (!symbolStart(first)) { throw new EdnSyntaxException("The " + label + " '" + ident + "' begins with a forbidden character."); } if ((first == '.' || first == '-') && ident.length() > 1 && isDigit(ident.charAt(1))) { throw new EdnSyntaxException("The " + label + " '" + ident + "' begins with a '-' or '.' followed by digit, " + "which is forbidden."); } int n = ident.length(); for (int i = 1; i < n; i++) { if (!CharClassify.symbolConstituent(ident.charAt(i))) { throw new EdnSyntaxException("The " + label + " '" + ident + "' contains the illegal character '" + ident.charAt(i) + "' at offset " + i + "."); } } }
9
public static StringBuffer cstats(CharStats E, char c, HTTPRequest httpReq, java.util.Map<String,String> parms, int borderSize) { final StringBuffer str=new StringBuffer(""); final PairVector<String,String> theclasses=new PairVector<String,String>(); if(httpReq.isUrlParameter(c+"CSTATS1")) { int num=1; String behav=httpReq.getUrlParameter(c+"CSTATS"+num); while(behav!=null) { if(behav.length()>0) { String prof=httpReq.getUrlParameter(c+"CSTATSV"+num); if(prof==null) prof="0"; prof=""+CMath.s_int(prof); theclasses.addElement(behav,prof); } num++; behav=httpReq.getUrlParameter(c+"CSTATS"+num); } } else { for(final int i : CharStats.CODES.ALLCODES()) { if(CMath.s_int(E.getStat(CharStats.CODES.NAME(i)))!=0) theclasses.addElement(CharStats.CODES.NAME(i),E.getStat(CharStats.CODES.NAME(i))); } } str.append("<TABLE WIDTH=100% BORDER="+borderSize+" CELLSPACING=0 CELLPADDING=0>"); for(int i=0;i<theclasses.size();i++) { final String theclass=theclasses.elementAt(i).first; str.append("<TR><TD WIDTH=35%>"); str.append("<SELECT ONCHANGE=\"EditAffect(this);\" NAME="+c+"CSTATS"+(i+1)+">"); str.append("<OPTION VALUE=\"\">Delete!"); str.append("<OPTION VALUE=\""+theclass+"\" SELECTED>"+theclass); str.append("</SELECT>"); str.append("</TD>"); str.append("<TD WIDTH=65%>"); str.append("<INPUT TYPE=TEXT NAME="+c+"CSTATSV"+(i+1)+" VALUE=\""+theclasses.elementAt(i).second+"\" SIZE=4 MAXLENGTH=4>"); str.append("</TD>"); str.append("</TR>"); } str.append("<TR><TD WIDTH=35%>"); str.append("<SELECT ONCHANGE=\"AddAffect(this);\" NAME="+c+"CSTATS"+(theclasses.size()+1)+">"); str.append("<OPTION SELECTED VALUE=\"\">Select a stat"); for(final int i : CharStats.CODES.ALLCODES()) { if(!theclasses.contains(CharStats.CODES.NAME(i))) str.append("<OPTION VALUE=\""+CharStats.CODES.NAME(i)+"\">"+CharStats.CODES.DESC(i)); } str.append("</SELECT>"); str.append("</TD>"); str.append("<TD WIDTH=65%>"); str.append("<INPUT TYPE=TEXT NAME="+c+"CSTATSV"+(theclasses.size()+1)+" VALUE=\"\" SIZE=4 MAXLENGTH=4>"); str.append("</TD>"); str.append("</TR>"); str.append("</TABLE>"); return str; }
9
@Override @JsonIgnore public void applyDefaultValues(boolean force) { if (force || sourceRoutingKey == null) { sourceRoutingKey = "#"; } if (force || requeue == null) { requeue = false; } if (force || number == null || number < 1) { number = 1; } }
7
* @param mvdPos the start-position of the first term in the mvd * @param firstTerm the first term of the query * @return the set of versions it was found in (may be empty) */ public BitSet find( String query, int mvdPos, String firstTerm ) { int pos = 0; String rhs = query; String lhs = ""; boolean found = false; BitSet bs = new BitSet(); int index = query.indexOf(firstTerm); if ( index > 0 ) { rhs = query.substring(index); lhs = query.substring(0,index); } for ( int i=0;i<pairs.size();i++ ) { Pair p = pairs.get(i); if ( p.length()+pos > mvdPos ) { for ( int v=p.versions.nextSetBit(0);v>=0;v=p.versions.nextSetBit(v+1) ) { found = findForward(rhs,i,mvdPos-pos,v); if ( found && lhs.length()>0 ) found = findBackward(lhs,i,(mvdPos-pos)-1,v); if ( found ) bs.set(v); } break; } pos += p.length(); } return bs; }
7
@XmlElementDecl(namespace = "http://www.w3.org/2001/04/xmlenc#", name = "AgreementMethod") public JAXBElement<AgreementMethodType> createAgreementMethod(AgreementMethodType value) { return new JAXBElement<AgreementMethodType>(_AgreementMethod_QNAME, AgreementMethodType.class, null, value); }
0
CountByType countMarkerTypes(Collection<Marker> markersToCount) { CountByType countByMarkerType = new CountByType(); for (Marker marker : markersToCount) { String type = markerTypes.getType(marker); String subtype = markerTypes.getSubType(marker); countByMarkerType.inc(type); if (subtype != null) countByMarkerType.inc(subtype); } return countByMarkerType; }
2
private boolean isSymmetricAndHasZeroDiagonal() throws NonZeroDiagonalException { boolean execute = true, result = true ; for(int i = 0 ; i < this.row ; i++) { for(int j = 0 ; j < this.col ; j++) { if(i != j && matrix[i][j] != matrix[j][i]) { //If the current entry is not on the main diagonal, and given that current entry //is matrix[i][j] and it is not equal to matrix[j][i] then the matrix is not //symmetric, so it must be fixed. System.out.print("matrix[" + i + "][" + j + "] = " + matrix[i][j] + " ") ; System.out.println("matrix[" + j + "][" + i + "] = " + matrix[j][i] + "\n Fixing matrix to be " + "symmetric...") ; if(matrix[i][j] == 0) { matrix[i][j] = 1 ; } else { matrix[j][i] = 1 ; } if(execute == true) { result = false ; //If any one entry comparison for symmetry returns false then there is //no point in setting result false again and again, so set execute to //to false to prevent this line from executing. execute = false ; } //If an entry on the main diagonal is not 0 then an exception is thrown. } else if(i == j && matrix[i][j] != 0) { throw new NonZeroDiagonalException("Diagonal entries are not all zero.") ; } } } return result ; }
8
public Configuration(ButtonWarpRandom plugin){ Configuration.plugin = plugin; plugin.getConfig().options().copyDefaults(true); plugin.getLogger().info("Configuration loaded!"); List<?> biomesInc = plugin.getConfig().getList("included-biomes"); for (Object b : biomesInc){ String biome = ((String)b).toUpperCase(); // Convert to upper try{ plugin.getLogger().info("Default Include Biome: " + biome); BiomesIncluded.add(Biome.valueOf(biome)); }catch (Exception ex){ plugin.getLogger().severe("Unknown Biome in configuration! '" + b + "'"); ex.printStackTrace(); } } List<?> biomesExcl = plugin.getConfig().getList("excluded-biomes"); for (Object b : biomesExcl){ String biome = ((String)b).toUpperCase(); // Convert to upper try{ plugin.getLogger().info("Default Exclude Biome: " + biome); BiomesExcluded.add(Biome.valueOf(biome)); }catch (Exception ex){ plugin.getLogger().severe("Unknown Biome in configuration! '" + biome + "'"); ex.printStackTrace(); } } plugin.saveConfig(); }
6
public void searchMultiTripFlightsPartTwo() { try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { System.out.println("Where is your MySQL JDBC Driver?"); e.printStackTrace(); } PreparedStatement ps = null; Connection con = null; ResultSet rs; try { con = DriverManager.getConnection("jdbc:mysql://mysql2.cs.stonybrook.edu:3306/mlavina", "mlavina", "108262940"); if (con != null) { con.setAutoCommit(false); String sql = "Create OR Replace view SearchResults(Name, FlightNo, DepTime, ArrTime, DepAirportID, ArrAirportID, LegNo, Class, fare, AirlineID)\n" + "as\n" + "SELECT DISTINCT R.Name, L.FlightNo, L.DepTime, L.ArrTime, L.DepAirportId, L.ArrAirportId, L.LegNo, M.Class, M.Fare, L.AirlineID\n" + "FROM Flight F, Leg L, Airport A , Fare M, Airline R\n" + "WHERE F.AirlineID = L.AirlineID AND F.FlightNo = L.FlightNo \n" + " AND (L.DepAirportId = ? OR L.ArrAirportId = ?) AND M.AirlineID = L.AirlineID \n" + "AND M.FlightNo = L.FlightNo AND R.Id = L.AirlineID AND M.FareType = 'Regular' \n" + "AND L.DepTime > ? AND L.DepTime < ? "; ps = con.prepareStatement(sql); ps.setString(1, flightMiddle); ps.setString(2, flightTo); ps.setDate(3, new java.sql.Date(returning.getTime())); ps.setDate(4, new java.sql.Date(returning.getTime() + +(1000 * 60 * 60 * 24))); try { ps.execute(); sql = "select Distinct A.Name, A.FlightNo, A.DepTime, B.ArrTime ,A.class, A.fare, A.DepAirportID, A.LegNo, A.AirlineID, B.ArrAirportID\n" + "From searchresults A, searchresults B\n" + "Where ((A.ArrAirportID = B.DepAirportID) OR (A.DepAirportID = ? AND B.ArrAirportID = ?))"; ps = con.prepareStatement(sql); ps.setString(1, flightMiddle); ps.setString(2, flightTo); ps.execute(); rs = ps.getResultSet(); flightReturnResults.removeAll(flightReturnResults); int i = 0; while (rs.next()) { //flightResults.add() flightReturnResults.add(new Flight(rs.getString("AirlineID"), rs.getString("Name"), rs.getInt("FlightNo"), rs.getTimestamp("DepTime"), rs.getTimestamp("ArrTime"), rs.getString("Class"), rs.getDouble("fare"), rs.getString("DepAirportID"), rs.getString("ArrAirportID"), i, rs.getInt("LegNo"))); i++; } con.commit(); } catch (Exception e) { con.rollback(); } } } catch (Exception e) { System.out.println(e); } finally { try { con.setAutoCommit(true); con.close(); ps.close(); } catch (Exception e) { e.printStackTrace(); } } }
6
public Expr parseExpression(String xpathExpression){ try { JaxenHandler handler = new JaxenHandler(); XPathReader reader = XPathReaderFactory.createReader(); reader.setXPathHandler(handler); //Parse an XPath expression, and send event callbacks to an XPathHandler. reader.parse(xpathExpression); XPathExpr xpath = handler.getXPathExpr(); return xpath.getRootExpr(); } catch (SAXPathException e) { e.printStackTrace(); return null; } }
1
public static void keyIndexedCounting(int[] a, int R) { int N = a.length; int[] count = new int[R + 1]; int[] aux = new int[N]; // count frequencies for (int i = 0; i < N; i++) count[a[i] + 1]++; // accumulate freq for (int r = 0; r < R; r++) count[r + 1] += count[r]; // sort for (int i = 0; i < N; i++) aux[count[a[i]]++] = a[i]; // copy for (int i = 0; i < N; i++) a[i] = aux[i]; }
4
public boolean waitForConnection() { if (connected) { log("error: connection has been already established"); return true; } if (connecting) { log("error: already waiting for client"); return true; } connecting = true; abortRequestSent = false; if (!serverSocketOpened) openServerSocket(); echo.waitForProbe(); Timer serverSocketTimer = new Timer(); serverSocketTimer.schedule(new TimerTask() { @Override public void run() { if (!connected) disconnect(false); } }, TIMEOUT); try { accessibleSocket = serverSocket.accept(); serverSocketTimer.cancel(); } catch (IOException e) { if (abortRequestSent) { log("waiting for a client aborted"); } else { disconnect(false); log("error: connection establishment unsuccessful"); logExceptionMessage(e); } serverSocketTimer.cancel(); return false; } if (!abortRequestSent) { try { inFromClient = new BufferedReader(new InputStreamReader( accessibleSocket.getInputStream())); outToClient = new PrintWriter( accessibleSocket.getOutputStream(), true); } catch (IOException e) { if (!abortRequestSent) disconnect(false); logExceptionMessage(e); return false; } connecting = false; connected = true; stability = STABLE; startPingThread(); log("new connection established"); return true; } else { connecting = false; accessibleSocket = null; return false; } }
9
private void setPreferredRaces() { if (!_raceLocked) { _raceBox.removeActionListener(_raceListener); _raceBox.removeAllItems(); Vector<BaseRace> preferred = _character.getRankedRaces(16); Vector<BaseRace> average = _character.getRankedRaces(15); Vector<BaseRace> poor = _character.getRankedRaces(14); for (BaseRace item : preferred) { _raceBox.addItem(item.getName()); } _raceBox.addItem(SEPARATOR); for (BaseRace item : average) { _raceBox.addItem(item.getName()); } _raceBox.addItem(SEPARATOR); for (BaseRace item : poor) { _raceBox.addItem(item.getName()); } _character.setRace(preferred.elementAt(0)); _raceBox.addActionListener(_raceListener); } }
4
private void addKompToList() { lblKompError.setVisible(false); DefaultListModel<AnstalldKompPlattNiva> dlm = (DefaultListModel<AnstalldKompPlattNiva>) listChosenKomp.getModel(); Kompetensdoman chosenKomp = (Kompetensdoman) cbKompNamn.getSelectedItem(); Plattform chosenPlat = (Plattform) cbKompPlattform.getSelectedItem(); String chosenNiva = cbNiva.getSelectedItem().toString().substring(5); boolean exists = false; // check if the kompetens is already added for (int i = 0; i < dlm.getSize() && !exists; i++) { AnstalldKompPlattNiva ack = dlm.get(i); if (ack.getKompetens().getKid() == chosenKomp.getKid()) { if (ack.getPlattform().getPid() == chosenPlat.getPid()) { exists = true; } } } if (!exists) { dlm.addElement(new AnstalldKompPlattNiva(chosenKomp, chosenPlat, Integer.parseInt(chosenNiva))); } else { lblKompError.setText("Kan inte lägga till " + chosenKomp.getBenamning() + " - " + chosenPlat.getBenamning() + " igen."); lblKompError.setVisible(true); } }
5
@Override public void run(){ while(!super.detener){ try{ if(!this.guerreroColaAtaques.isEmpty()) recibirdaño(); if(this.objectivo.x==0&&this.objectivo.y==0) this.objectivo=getObjectivo(); //segundos que dura en durar al proximo cuadro en la matriz int segundos = 20 * espera; if(this.espacio.equals(this.refLabel.getLocation())){ atacar(); } else{ mover(); } sleep(segundos); }catch (InterruptedException ex){} } ImageIcon iconLogo; iconLogo = new ImageIcon(IMG.getImage("blood.png")); this.refLabel.setDisabledIcon(iconLogo); }
6
public void scrollCellToView(JTable table, int rowIndex, int vColIndex) { if (!(table.getParent() instanceof JViewport)) { return; } JViewport viewport = (JViewport) table.getParent(); Rectangle rect = table.getCellRect(rowIndex, vColIndex, true); Rectangle viewRect = viewport.getViewRect(); int x = viewRect.x; int y = viewRect.y; if (rect.x >= viewRect.x && rect.x <= (viewRect.x + viewRect.width - rect.width)){ } else if (rect.x < viewRect.x){ x = rect.x; } else if (rect.x > (viewRect.x + viewRect.width - rect.width)) { x = rect.x - viewRect.width + rect.width; } if (rect.y >= viewRect.y && rect.y <= (viewRect.y + viewRect.height - rect.height)){ } else if (rect.y < viewRect.y){ y = rect.y; } else if (rect.y > (viewRect.y + viewRect.height - rect.height)){ y = rect.y - viewRect.height + rect.height; } viewport.setViewPosition(new Point(x,y)); }
9
public static Cons removeDuplicatesFromLongList(Cons self, boolean equaltestP) { { int tablesize = Native.ceiling(self.length() * 0.3); Cons[] table = new Cons[tablesize]; Cons cursor = self; Stella_Object item = null; Cons bucket = null; int bucketindex = 0; { int i = Stella.NULL_INTEGER; int iter000 = 0; int upperBound000 = tablesize - 1; for (;iter000 <= upperBound000; iter000 = iter000 + 1) { i = iter000; table[i] = Stella.NIL; } } while (!(cursor == Stella.NIL)) { item = cursor.value; bucketindex = (((item.hashCode_()) & 0x7FFFFFFF) % tablesize); bucket = table[bucketindex]; { boolean foundP000 = false; { Stella_Object it = null; Cons iter001 = bucket; loop002 : for (;!(iter001 == Stella.NIL); iter001 = iter001.rest) { it = iter001.value; if ((equaltestP ? Stella_Object.equalP(it, item) : Stella_Object.eqlP(it, item))) { foundP000 = true; break loop002; } } } if (foundP000) { cursor.value = null; } else { table[bucketindex] = Cons.cons(item, bucket); } } cursor = cursor.rest; } return (self.remove(null)); } }
6
private Object handleForm(Object tos) { if (tos instanceof GedcomVersion && ((GedcomVersion)tos).getForm() == null) { return new FieldRef(tos, "Form"); } else if (tos instanceof Media && ((Media)tos).getFormat() == null) { return new FieldRef(tos, "Format"); } return null; }
4
private String[] getLogToFilesPropertyValue(final Properties properties) { String values = this.getPropertyValue(properties, LOG_TO_FILES_TAG, null); if (values == null) { return null; } return values.split(OUTPUT_SEPARATOR); }
1
protected Element createAutomatonElement(Document document, Automaton auto, String name) { Element se = document.getDocumentElement(); Element be = createElement(document, name, null, null); se.appendChild(be); //System.out.println("auto: " + auto); writeFields(document, auto, be); return be; }
0
public void setValueAt(Object value, int row, int column) { despaceSet((String) value, entries[row][column - 1]); fireTableCellUpdated(row, column); }
0
Class33(GameMode class230, int i, IndexLoader class45) { do { try { aClass45_458 = class45; if (aClass45_458 == null) break; int i_6_ = -1 + aClass45_458.getAmountChildren(); aClass45_458.getAmountChildEntries(i_6_); } catch (RuntimeException runtimeexception) { throw Class348_Sub17.method2929(runtimeexception, ("iba.<init>(" + (class230 != null ? "{...}" : "null") + ',' + i + ',' + (class45 != null ? "{...}" : "null") + ')')); } break; } while (false); }
5
public BoundaryBox getBB(){ return bb; }
0
private PortalScript getPortalScript(String scriptName) { if (scripts.containsKey(scriptName)) { return scripts.get(scriptName); } File scriptFile = new File("scripts/portal/" + scriptName + ".js"); if (!scriptFile.exists()) { scripts.put(scriptName, null); return null; } FileReader fr = null; ScriptEngine portal = sef.getScriptEngine(); try { fr = new FileReader(scriptFile); CompiledScript compiled = ((Compilable) portal).compile(fr); compiled.eval(); } catch (ScriptException e) { log.error("THROW "+scriptName+" ", e); } catch (IOException e) { log.error("THROW "+scriptName+" ", e); } finally { if (fr != null) { try { fr.close(); } catch (IOException e) { log.error("ERROR CLOSING", e); } } } PortalScript script = ((Invocable) portal).getInterface(PortalScript.class); scripts.put(scriptName, script); return script; }
6
public void lisaaJonoonArvollinen(Arvollinen lisattava) throws IllegalArgumentException, IllegalStateException { if (lisattava == null) { throw new IllegalArgumentException(); } if (seuraavaArvollinen != null) { throw new IllegalStateException(); } this.seuraavaArvollinen = lisattava; }
2
private boolean canCastleQueenSide( int position ) { return ( !hasPieceMoved( pieceAt( position ) ) && !kingInCheck() && pieceTypeAt( position + 3 ) == ROOK && !hasPieceMoved( pieceAt( position - 4 ) ) && squareEmpty( position - 1 ) && !squareAttacked( position - 1 ) && squareEmpty( position - 2 ) && !squareAttacked( position - 2 ) && squareEmpty( position - 3 ) && !squareAttacked( position - 3 ) ); }
9
public void setTextFill(float textFill) { if(textFill == -1) this.textFill = getLength(); else this.textFill = textFill; }
1
public void removeVisitor(Element element) { elements.remove(element); }
0
static boolean SendMessage(ForwarderMessage message){ if (message.to.equalsIgnoreCase(Setup.ROUTER_NAME)) { // we are the target Setup.println("<<Received Incoming Message to ME from " + message.from + ">>\n" + message.text + "\n"); return true; } InetAddress addr = null; try { Setup.println("[ForwardingService.SendMessage] Creando socket a " + message.to); for(NbrCostPair nbr : Setup.nbrList){ if (RoutingService.next.containsKey(message.to) && nbr.getNbr().getId().equalsIgnoreCase(RoutingService.next.get(message.to))) addr = nbr.getNbr().getAddr(); } Socket socket = new Socket(addr, Setup.FORWARDING_PORT); Setup.println("[ForwardingService.SendMessage] Enviando mensaje a " + addr.getHostAddress()); DataOutputStream out = new DataOutputStream(socket.getOutputStream()); out.writeBytes(message.toString()); out.flush(); socket.close(); } catch (Exception e) { Setup.println("[ForwardingService.SendMessage] No es posible enviar mensaje al destino " + e.getMessage()); return false; } //JOptionPane.showMessageDialog(null, "El mensaje ha sido enviado a " + message.to); return true; }
5
private void addOximata(){ /* * vazei ta oximata apo thn vash sthn dropdown lista */ ArrayList<String> oximata=con.getOximata(); //pairnei ta oximata apo tin vasi kai ta apothikeui sthn ArrayList<String> for(int i=0;i<oximata.size();i++){ oximataBox.addItem(oximata.get(i)); //prostheti to oxima sthn dropdown lista } }
1
public static void addNanoPostsIntoTree(ArrayList<NanoPost> npList, JTree tree, NBFrame nbf) { // Add all OP posts and their child posts in tree DefaultMutableTreeNode rootNode = (DefaultMutableTreeNode)tree.getModel().getRoot(); for (NanoPost np : npList) { DefaultMutableTreeNode npOpNode = new DefaultMutableTreeNode(new NanoPostTreeItem(np, nbf)); if (np.isOpPost()) { addChildsAsNodes(np, npOpNode, nbf); rootNode.add(npOpNode); } } }
2
public void run() { theLogger.info("Entering the Client Worker Thread :: "+threadId); try { registerCommands(); } catch (ServiceException ex) { theLogger.log(Level.SEVERE, "Unable to register the commmands: impossible to proceed", ex); try { sessionSocket.close(); } catch (IOException ex1) { theLogger.log(Level.SEVERE, "Error Caught in closing the client socket", ex1); } return; } try { // initializing the streams cmdReader = new BufferedReader( new InputStreamReader(sessionSocket.getInputStream())); responseWriter = new PrintWriter(sessionSocket.getOutputStream(), true); // show welcome display responseWriter.print(display.welcomeDisplay()); responseWriter.flush(); // server while: it waits command forwarded by the client theLogger.info("Thread correctly initialized :: READY to accept commands..."); String clientQuery = ""; String clientResponse = ""; boolean parsingOutcome; while(sessionOpen) { clientQuery = cmdReader.readLine(); theLogger.info("Treating the command query :: " +clientQuery); // normal management flow parsingOutcome = parser.isValidQuery(clientQuery); if(!parsingOutcome) { responseWriter.print(display.errorDisplay(clientQuery)); responseWriter.flush(); continue; } // command validated ClientCommand cmd = parser.buildCommand(clientQuery); if(cmd == null) { responseWriter.print(display.errorDisplay(clientQuery)); responseWriter.flush(); continue; } // command correctly built clientResponse = interpreter.interpretCommand(cmd); if(clientResponse.contains("${RELEASE}")) { clientResponse = clientResponse.replace("${RELEASE}", ""); sessionOpen = false; theLogger.info("Session released as requested by the client"); } responseWriter.print(display.decoratedDisplay(clientResponse)); responseWriter.flush(); } } catch (IOException ex) { theLogger.log(Level.SEVERE, "Error Caught: I/O exception, unable to proceed", ex); } catch (ServiceException ex) { theLogger.log(Level.SEVERE, "Error Caught: Interpreter Unable to interpret the Query", ex); }finally { try { sessionSocket.close(); responseWriter.close(); } catch (IOException ex) { theLogger.log(Level.SEVERE, "Error Caught in closing the client socket", ex); } } }
9
public Image hsi_adjust(Image im, int width, int height, int hue, int saturation, int brightness) { // The hue, saturation, and brightness variables represent values in the range // from -100 to 100. -100 is a full decrease in value, 0 is no change, and 100 is a full // increase. // NOTE: Brightness is the same as Intensity. I use "brightness" to be consistent // with the Color class's terminology. int pix[] = JIPTUtilities.getPixelArray(im); int new_pix[] = new int[width*height]; for(int i = 0; i < pix.length; i++) { //////// Get pixels /////////////////// int alpha = (pix[i] >> 24) & 0xff; int red = (pix[i] >> 16) & 0xff; int green = (pix[i] >> 8) & 0xff; int blue = (pix[i] ) & 0xff; // Get HSB for this pixel float hsb_array[] = Color.RGBtoHSB(red, green, blue, null); ///////////////////////////// /// Get new HSB values ////// ///////////////////////////// /////////////////// ///// Hue ///////// /////////////////// float degree_hue = hsb_array[0]*360.0f; degree_hue = degree_hue + (hue*360.0f/100.0f); if(degree_hue > 360.0f) degree_hue = degree_hue - 360.0f; else if(degree_hue < 0.0f) degree_hue = degree_hue + 360; hsb_array[0] = degree_hue/360.0f; //////////////////////// ///// Saturation /////// //////////////////////// if(saturation <= 0) hsb_array[1] = hsb_array[1] + saturation*hsb_array[1]/100.0f; else hsb_array[1] = hsb_array[1] + saturation*(hsb_array[1])/100.0f; // hsb_array[1] = 1; //////////////////////// //// Put in range ////// //////////////////////// if(hsb_array[0] > 1) hsb_array[0] = 1; if(hsb_array[1] > 1) hsb_array[1] = 1; if(hsb_array[2] > 1) hsb_array[2] = 1; //System.out.println("HSI = " + hsb_array[0] + " " + hsb_array[1] + " " + hsb_array[2]); Color new_color = new Color(Color.HSBtoRGB(hsb_array[0], hsb_array[1], hsb_array[2])); red = new_color.getRed(); green = new_color.getGreen(); blue = new_color.getBlue(); //////////////////////////////////////// //// Adjust brightness in RGB domain /// /////////////////////////////////////// red = red + (int) ((brightness/100.0)*255); green = green + (int) ((brightness/100.0)*255); blue = blue + (int) ((brightness/100.0)*255); ///// Put in correct range (0...255) ///// red = putInRange(red); green = putInRange(green); blue = putInRange(blue); ///////////////////////////////////////////// ///////////// Put in new pixel array //////// ///////////////////////////////////////////// new_pix[i] = 0; new_pix[i] += (alpha << 24); // alpha new_pix[i] += (red << 16); // r new_pix[i] += (green << 8); // g new_pix[i] += (blue ); // b } Image new_im = Toolkit.getDefaultToolkit().createImage(new MemoryImageSource(width, height, new_pix, 0, width)); return new_im; }
7
public void acquirePowerUp(PowerUp powerUp) { // remove it from the map map.removeSprite(powerUp); if (powerUp instanceof PowerUp.Star) { // do something here, like give the player points soundManager.play(prizeSound); } else if (powerUp instanceof PowerUp.Music) { // change the music soundManager.play(prizeSound); toggleDrumPlayback(); } else if (powerUp instanceof PowerUp.Goal) { // advance to next map soundManager.play(prizeSound, new EchoFilter(2000, .7f), false); map = resourceManager.loadNextMap(); } }
3
public void insertObjects(ConnectionWrapper cw, ProtectionManager protectionManager) throws SQLException { ArrayList<InsertionObject> toRemove = new ArrayList<InsertionObject>(); for (InsertionObject i : buffer) { // insert the object Long id = persist.saveObjectUnprotected(cw, i.getInsertionObject(), this); // get the object id if (id != null) { // update the referring table entry StringBuilder sb = new StringBuilder("UPDATE "); sb.append(i.getTableName()); sb.append(" SET "); sb.append(i.getColumnName()); sb.append(" = ?"); sb.append(" WHERE "); sb.append(Defaults.ID_COL); sb.append(" = ?"); PreparedStatement ps = cw.prepareStatement(sb.toString()); ps.setLong(1, id); ps.setLong(2, i.getParentId()); Tools.logFine(ps); try { int updated = ps.executeUpdate(); // make sure only one object was updated. if (updated != 1) { throw new SQLException("Updated " + updated + ", not 1."); } // add a protection entry String tableName = null; if (i.getReferenceType().isArray()) { tableName = NameGenerator.getArrayTablename(persist.getAdapter()); } else { tableName = NameGenerator.getTableName(i.getReferenceType(), persist.getAdapter()); } protectionManager.protectObjectInternal(i.getTableName(), i .getParentId(), i.getColumnName(), tableName, id, NameGenerator.getSystemicName(i.getInsertionObject() .getClass()), cw); // if the object was successfully inserted, remove it // from the buffer. toRemove.add(i); } finally { ps.close(); } } } for (InsertionObject i : toRemove) { buffer.remove(i); } }
5
@Override public Team[] balance(Player[] players) { int playersByTeam = players.length / 2; Team team1 = new Team(playersByTeam); Team team2 = new Team(playersByTeam); Team t1; Team t2; int playersInT1; int playersInT2; int difference = 0; for (Player player : players) { difference += player.getScore(); } final BinaryWordInterface binaryWord; if (binaryWordClazz == BinaryWord.class) { binaryWord = new BinaryWord(players.length); } else { binaryWord = new RealBinaryWord(); } do { // In order to have the same number of players in both teams if (binaryWord.bitsAtTrue() == playersByTeam) { t1 = new Team(playersByTeam); t2 = new Team(playersByTeam); playersInT1 = 0; playersInT2 = 0; for (int i = 0; i < players.length; i++) { if (binaryWord.bitAt(i)) { t1.setPlayerAt(playersInT1, players[i]); playersInT1++; } else { t2.setPlayerAt(playersInT2, players[i]); playersInT2++; } } // Check if we find better balanced teams if (Math.abs(t1.getScore() - t2.getScore()) < difference) { team1 = t1; team2 = t2; difference = Math.abs(t1.getScore() - t2.getScore()); } } binaryWord.increment(); } while (binaryWord.toInteger() < Math.pow(2, players.length)); return new Team[] { team1, team2 }; }
7
public static void main(String[] args) { BlackJackGame bjg; Scanner stdin=new Scanner(in); String prompt; boolean shouldRun=true; out.println("Welcome to BlackJack!"); out.println("What is your name?"); String name = stdin.nextLine(); out.println("How many decks do you want to play?"); int numOfDecks=Integer.parseInt(stdin.nextLine()); out.println("You are playing with "+numOfDecks+" Decks."); bjg=new BlackJackGame(numOfDecks,name); do{ if(bjg.remainingCard()<10){ out.println("There are not enough cards to play!\n" + "The game will now exit"); break; } bjg.start(); while(!bjg.getPlayer().isBusted()){ out.println("Do you want to hit? (y/n)"); prompt=stdin.nextLine(); if(prompt.charAt(0)=='Y'||prompt.charAt(0)=='y') bjg.playerHit(); else break; } if(!bjg.getPlayer().isBusted()) bjg.houseHit(); bjg.result(); out.println("\nDo you want to continue? (y/n)"); prompt=stdin.nextLine(); if(prompt.charAt(0)=='N'||prompt.charAt(0)=='n') shouldRun=false; bjg.clearHands(); }while(shouldRun); out.println("Thanks for playing, Bye!"); stdin.close(); }
8
public int update(String[] updateStrings) { DBConnection DBToUse=null; int Result=-1; String updateString=null; try { DBToUse=DBFetch(); for (final String updateString2 : updateStrings) { updateString=updateString2; try { Result=DBToUse.update(updateString,0); } catch(final Exception sqle) { if(sqle instanceof java.io.EOFException) { Log.errOut("DBConnections",""+sqle); DBDone(DBToUse); return -1; } if(sqle instanceof SQLException) { // queued by the connection for retry } } if(Result<0) { Log.errOut("DBConnections",""+DBToUse.getLastError()+"/"+updateString); } } } catch(final Exception e) { enQueueError(updateString,""+e,""+0); reportError(); Log.errOut("DBConnections",""+e); } finally { if(DBToUse!=null) DBDone(DBToUse); } return Result; }
7
public boolean nextP() { { StellaHashTableIterator self = this; { KvCons cursor = self.bucketCursor; if (self.firstIterationP) { self.firstIterationP = false; } else if (cursor != null) { cursor = cursor.rest; } if (cursor == null) { { KvCons[] table = self.bucketTable; int index = self.bucketIndex; int size = self.size; if (table == null) { return (false); } while ((cursor == null) && (index < size)) { cursor = table[index]; index = index + 1; } self.bucketIndex = index; self.bucketCursor = cursor; } } if (cursor != null) { self.key = cursor.key; self.value = cursor.value; self.bucketCursor = cursor; return (true); } else { return (false); } } } }
7
@Override public int hashByteArray(byte[] array) { final int c1 = 0xcc9e2d51; final int c2 = 0x1b873593; int length = array.length; int h1 = 0xdeadbeef ^ length; int pt = 0; while(length >= 4){ int k1 = (array[pt] & 0xFF) << 24; k1 |= (array[pt + 1] & 0xFF) << 16; k1 |= (array[pt + 2] & 0xFF) << 8; k1 |= (array[pt + 3] & 0xFF); k1 *= c1; k1 = (k1 << 15) | (k1 >>> 17); k1 *= c2; h1 ^= k1; h1 = (h1 << 13) | (h1 >>> 19); h1 = h1*5+0xe6546b64; pt += 4; length -=4; } int k1 = 0; switch(length) { case 3: k1 = (array[pt + 2] & 0xFF) << 16; case 2: k1 |= (array[pt + 1] & 0xFF) << 8; case 1: k1 |= (array[pt] & 0xFF); k1 *= c1; k1 = (k1 << 15) | (k1 >>> 17); k1 *= c2; h1 ^= k1; } h1 ^= length; h1 ^= h1 >>> 16; h1 *= 0x85ebca6b; h1 ^= h1 >>> 13; h1 *= 0xc2b2ae35; h1 ^= h1 >>> 16; return h1; }
4
public void setToZero(){ beings.clear(); for (Being being: zeroBeings){ if (being.isHuman()){ beings.add(new Human(being.getX(), being.getY())); } if (being.isZombie()){ beings.add(new Zombie(being.getX(), being.getY())); } } }
3
@Override public boolean equals(Object obj) { if (!(obj instanceof TVC)) { return false; } return id == ((TVC) obj).id; }
1
@Override public void onFirstUpdate(){ if(ParticleSystem.isEnabled()){ // XXX DANGER WILL ROBINSON XXX List<Vector3f> hotSpots = getHotSpotsFor("Engine"); if( hotSpots == null) { // No Engine hotspots defined return; } for(Vector3f v : hotSpots){ final Vector3f hotspot = v; final Actor a = this; ParticleGenerator<? extends Particle> particleGenerator = new graphics.particles.generators.Exhaust<Plasma>(Plasma.class, new actor.interfaces.Movable() { @Override public Vector3f getVelocity() { return a.getVelocity(); } @Override public Object setVelocity(Vector3f vel) { // NOT IMPLEMENTED return null; } @Override public Vector3f getPosition() { return a.getPosition().plus(hotspot); } @Override public Object setPosition(Vector3f newPosition) { // NOT IMPLEMENTED return null; } @Override public Quaternion getRotation() { return a.getRotation(); } @Override public Object setRotation(Quaternion rot) { // NOT IMPLEMENTED return null; } }); if (particleGenerators != null) particleGenerators.add(particleGenerator); ParticleSystem.addGenerator(particleGenerator); } } }
5
public ModeloCliente(ControladorCliente c) { controlador = c; ParseadorDeXML parser = new ParseadorDeXML(); if (!parser.chequearSiExisteXML(ControladorCliente.ARCHIVO_CONEXION)) parser.crearXML(ControladorCliente.BACKUP_CONEXION, ControladorCliente.ARCHIVO_CONEXION); parser.parsearXML(ControladorCliente.ARCHIVO_CONEXION); servidor = parser.obtenerValor(ParseadorDeXML.SERVIDOR); puerto = Integer.valueOf(parser.obtenerValor(ParseadorDeXML.PUERTO)); }
1
public String getNote() { return note; }
0
@Override public void execute(CommandSender sender, String[] arg1) { if (!CommandUtil.hasPermission(sender, PERMISSION_NODES)) { sender.sendMessage(plugin.NO_PERMISSION); return; } if (arg1.length < 1) { sender.sendMessage(ChatColor.RED + "/" + plugin.ban + " (PlayerName) (message)"); return; } try { if (plugin.getUtilities().playerExists(arg1[0])) { String message = plugin.DEFAULT_BAN_PLAYER; if (arg1.length > 1) { message = ""; for (String data : arg1) { if (!data.equalsIgnoreCase(arg1[0])) ; message += data + " "; } } plugin.getUtilities().banPlayer(arg1[0], message); String bmessage = plugin.BAN_MESSAGE_BROADCAST.replace("%player", arg1[0]); bmessage = bmessage.replace("%sender", sender.getName()); bmessage = bmessage.replace("%message", message); plugin.getUtilities().sendBroadcast(bmessage); } else { sender.sendMessage(plugin.PLAYER_NOT_EXIST); } } catch (SQLException e) { e.printStackTrace(); } }
7
@Override public double getValue(int row, int col) throws MatrixIndexOutOfBoundsException { if ((row < 0) || (col < 0) || (row >= mas.length) || (col >= mas[0].length)) { throw new MatrixIndexOutOfBoundsException("Inadmissible value of an index."); } return mas[row][col]; }
4
public void testStaticQueryInvalidSourceText2() { String goal = "p(]"; try { Query.hasSolution(goal); // should throw exception fail(goal + " (bad syntax) succeeded"); // shouldn't get to here } catch (org.jpl7.PrologException e) { // expected exception if (e.term().hasFunctor("error", 2) && e.term().arg(1).hasFunctor("syntax_error", 1) && e.term().arg(1).arg(1).hasFunctor("cannot_start_term", 0)) { // OK: an appropriate exception was thrown } else { fail(goal + " (bad syntax) threw wrong PrologException: " + e); } } catch (Exception e) { fail(goal + " (bad syntax) threw wrong exception class: " + e); } }
5
@Override public void run(){ try { Registry reg = LocateRegistry.createRegistry(Util.puertoServidor); ServidorCentral servidor = new ServidorCentral(); reg.rebind("servidor",servidor); } catch (Exception e) { e.printStackTrace(); } System.out.println("-> Servidor central inicializado."); int contadorBorrados; while (true) { contadorBorrados = 0; try { TimeUnit.SECONDS.sleep(10); } catch (Exception e) { e.printStackTrace(); } ListaSucursal sucursalesActivas = SucursalesArchivoXml.buscarSucursalesActivas(new Sucursal()); for (int i = 0; i < sucursalesActivas.getListaSucursal().size();i++) { try { Registry reg = LocateRegistry.getRegistry(sucursalesActivas.getListaSucursal().get(i).getIp(),Util.puertoServidorSucursal); SucursalInterfaz servidorSucursal = (SucursalInterfaz) reg.lookup("servidor"); servidorSucursal.estaActivo(); } catch (Exception e) { SucursalesArchivoXml.eliminarSucursal(sucursalesActivas.getListaSucursal().get(i).getIp()); contadorBorrados++; } } if(contadorBorrados > 0) { sucursalesActivas = SucursalesArchivoXml.buscarSucursalesActivas(new Sucursal()); for(int i=0; i<sucursalesActivas.getListaSucursal().size(); i++) { try { Registry reg = LocateRegistry.getRegistry(sucursalesActivas.getListaSucursal().get(i).getIp(),Util.puertoServidorSucursal); SucursalInterfaz servidorSucursal = (SucursalInterfaz) reg.lookup("servidor"); ListaSucursal sucursalesActivasEnOtras = SucursalesArchivoXml.buscarSucursalesActivas(sucursalesActivas.getListaSucursal().get(i)); Sucursal sucursalDerecha = SucursalesArchivoXml.buscarSucursalPorIp(sucursalesActivas.getListaSucursal().get(i).getIp(), true); Sucursal sucursalIzquierda = SucursalesArchivoXml.buscarSucursalPorIp(sucursalesActivas.getListaSucursal().get(i).getIp(), false); servidorSucursal.cambiarEstado(sucursalesActivasEnOtras, sucursalDerecha, sucursalIzquierda); } catch (Exception e) { System.out.println (e); } } } } }
8
private double calculatePearson() { double total1 = 0, total2 = 0; for (int i = 0; i < itemIds.length; i++) { total1 += ratings1[i]; total2 += ratings2[i]; } double average1 = total1 / itemIds.length, average2 = total2 / itemIds.length; double numerator = 0, denominator1 = 0, denominator2 = 0; for (int i = 0; i < itemIds.length; i++) { double calc1 = ratings1[i] - average1, calc2 = ratings2[i] - average2; numerator += calc1 * calc2; denominator1 += calc1 * calc1; denominator2 += calc2 * calc2; } double denominator = Math.sqrt(denominator1 * denominator2); if (denominator == 0.0) return 0; else return numerator / denominator; }
3