text
stringlengths
14
410k
label
int32
0
9
@Override public void paintComponent (Graphics g) { if (isActive) if (isHovered) AHOVER.paintIcon (this, g, 0, 0); else ACTIVE.paintIcon (this, g, 0, 0); else if (isHovered) IHOVER.paintIcon (this, g, 0, 0); else INACTIVE.paintIcon (this, g, 0, 0); }
3
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(RegExpForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(RegExpForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(RegExpForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(RegExpForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new RegExpForm().setVisible(true); } }); }
6
private List<Long> pickNextEdgeFrom_Using_(Long currHeadVertice, Set<Long> usableEdges) { Set<Long> incident = graph.getIncident(currHeadVertice); countAccess(1); // build the set of usable edges connected witht the head Set<Long> intersect = new HashSet<>(usableEdges); intersect.retainAll(incident); // this set has to have atleast one edge! if (intersect.isEmpty()) { throw new IllegalArgumentException( " <<< --- whoooooops!!! --- >>> \nArguments: " + currHeadVertice + " and " + usableEdges); } // fetch the edge Long edge = NULL_IDX; for (Long e : intersect) { // java has no better way of getting a single // elem out of a set -_- edge = e; break; } // fetch the vertice Long vertice = NULL_IDX; for (Long v : graph.getSourceTarget(edge)) { countAccess(1); if (v != currHeadVertice) { vertice = v; } } if (vertice == NULL_IDX || edge == NULL_IDX) { throw new IllegalArgumentException( " <---- Nil! ----> \nArguments: " + currHeadVertice + " and " + usableEdges); } // pack and return return new ArrayList<>(Arrays.asList(edge, vertice)); }
6
@Override protected void createRadioGroups() { Map<String, ButtonGroup> tempRadioGroupMap = new HashMap<String, ButtonGroup>(); for ( SwingWidget<?> widget : swingWidgetMap.values() ) { if ( widget.getControl() instanceof RadioButtonT && ( (RadioButtonT) widget.getControl() ).getRadioGroup() != null && ( (RadioButtonT) widget.getControl() ).getRadioGroup() != "" ) { String rg = ( (RadioButtonT) widget.getControl() ).getRadioGroup(); if ( !tempRadioGroupMap.containsKey( rg ) ) tempRadioGroupMap.put( rg, new ButtonGroup() ); if ( widget instanceof SwingButtonWidget ) { tempRadioGroupMap.get( rg ).add(((SwingButtonWidget) widget).getButton() ); } } } radioGroupMap = tempRadioGroupMap; }
7
protected boolean step() { controller.step(); return true; }
0
public static int BitsInByte(byte b) { int ret = 8; for (int i = 7; i >= 0; i++) if (b << i == 0) ret--; else break; return ret; }
2
private void createSashFormContent() { sash = new Sash (mainComposite, SWT.VERTICAL); final FormLayout formLayout = new FormLayout(); mainComposite.setLayout(formLayout); FormData treeLayoutFormData = new FormData (); treeLayoutFormData.left = new FormAttachment (0, 0); treeLayoutFormData.right = new FormAttachment (sash, 0); treeLayoutFormData.top = new FormAttachment (0, 0); treeLayoutFormData.bottom = new FormAttachment (100, 0); tree.setLayoutData (treeLayoutFormData); final int limit = 50, percent = 30; final FormData sashData = new FormData (); sashData.left = new FormAttachment (percent, 0); sashData.top = new FormAttachment (0, 0); sashData.bottom = new FormAttachment (100, 0); sash.setLayoutData (sashData); sash.addListener (SWT.Selection, new Listener () { public void handleEvent (Event e) { Rectangle sashRect = sash.getBounds (); Rectangle shellRect = mainComposite.getClientArea (); int right = shellRect.width - sashRect.width - limit; e.x = Math.max (Math.min (e.x, right), limit); if (e.x != sashRect.x) { sashData.left = new FormAttachment (0, e.x); mainComposite.layout (); } } }); FormData editorLayoutFormData = new FormData(); editorLayoutFormData.left = new FormAttachment (sash, 0); editorLayoutFormData.right = new FormAttachment (100, 0); editorLayoutFormData.top = new FormAttachment (0, 0); editorLayoutFormData.bottom = new FormAttachment (100, 0); editor.setLayoutData(editorLayoutFormData); }
1
public static void pause(){ //Allow players to pause their game, thanks for the help - got it working if(EZInteraction.wasKeyPressed('y') || pause){ if(EZInteraction.wasKeyPressed('y')) pause = !pause; if(EZInteraction.wasKeyPressed('b')) pongRun = !pongRun; if(EZInteraction.wasKeyPressed('v')){ //Reset the players' current score PongScore.resetScore(); PongMessage.scoreMessage(); } PongSound.stopSound("all"); PongMessage.showMessage(); } }
5
private boolean anyMovement() { if (backward || forward || right || left) { return true; } return false; }
4
protected void updateButtonState() { Component newTabComponent = displayPanes.getSelectedComponent(); run.setEnabled(false); if (newTabComponent instanceof JScrollPane) { newTabComponent = ((JScrollPane) newTabComponent).getViewport().getView(); } if (newTabComponent instanceof CodeTextPane) { CodeTextPane codeText = (CodeTextPane) newTabComponent; if (codeText.getCodeFile() != null && codeText.getOriginFile().isJavaFile()) { compileFocus = codeText.getCodeFile(); compile.setEnabled(true); if (compileFocus.isCompiled() || compileFocus.checkForCompiledFile() != null) { if (compileFocus.getLastCompilation() == null) compileFocus.checkForCompiledFile(); if (compileFocus.getLastCompilation() != null) run.setEnabled(compileFocus.getLastCompilation().isRunnable()); } } } }
8
private static int[] merge(int[] left, int[] right){ int l=0, r=0; int[] ret = new int[left.length+right.length]; int index = 0; while(l<left.length && r<right.length){ if(left[l]<right[r]){ ret[index++]=left[l++]; } else { ret[index++]=right[r++]; } } while(l<left.length){ ret[index++]=left[l++]; } while(r<right.length){ ret[index++]=right[r++]; } return ret; }
5
RLOGDatatypeProperties() { this.uri = "http://persistence.uni-leipzig.org/nlp2rdf/ontologies/rlog#" + name(); }
0
public Boolean checkBuiltIn(Location loc, Player play, Boolean isBreak){ if(!this.getBuiltIn().containsKey(play.getWorld())) this.getBuiltIn().put(play.getWorld(), true); if(isBreak){ if(this.hPlayerBreakBlock.containsKey(loc)) if(this.hPlayerBreakBlock.get(loc).contains(play)){ return true; } else{ return false; } else{ return false; } } else{ if(this.hPlayerPlaceBlock.containsKey(loc)) if(this.hPlayerPlaceBlock.get(loc).contains(play)){ return true; } else{ return false; } else{ return false; } } }
6
@EventHandler public void GhastHarm(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.getZombieConfig().getDouble("Ghast.Harm.DodgeChance") / 100; final double ChanceOfHappening = random.nextDouble(); if (ChanceOfHappening >= randomChance) { dodged = true; } if (damager instanceof Fireball) { Fireball a = (Fireball) event.getDamager(); LivingEntity shooter = a.getShooter(); if (plugin.getGhastConfig().getBoolean("Ghast.Harm.Enabled", true) && shooter instanceof Ghast && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) { Player player = (Player) e; player.addPotionEffect(new PotionEffect(PotionEffectType.HARM, plugin.getGhastConfig().getInt("Ghast.Harm.Time"), plugin.getGhastConfig().getInt("Ghast.Harm.Power"))); } } }
7
public void setFace() { if (_value < 11) { _face = ((Integer)_value).toString(); } else if (_value == 11) { _face = "jack"; } else if (_value == 12) { _face = "queen"; } else if (_value == 13) { _face = "king"; } else { _face = "ace"; } }
4
public double getCategoryJava2DCoordinate(CategoryAnchor anchor, int category, int categoryCount, Rectangle2D area, RectangleEdge edge) { double result = 0.0; Rectangle2D adjustedArea = area; CategoryPlot plot = (CategoryPlot) getPlot(); CategoryItemRenderer renderer = plot.getRenderer(); if (renderer instanceof Effect3D) { Effect3D e3D = (Effect3D) renderer; double adjustedX = area.getMinX(); double adjustedY = area.getMinY(); double adjustedW = area.getWidth() - e3D.getXOffset(); double adjustedH = area.getHeight() - e3D.getYOffset(); if (edge == RectangleEdge.LEFT || edge == RectangleEdge.BOTTOM) { adjustedY += e3D.getYOffset(); } else if (edge == RectangleEdge.RIGHT || edge == RectangleEdge.TOP) { adjustedX += e3D.getXOffset(); } adjustedArea = new Rectangle2D.Double(adjustedX, adjustedY, adjustedW, adjustedH); } if (anchor == CategoryAnchor.START) { result = getCategoryStart(category, categoryCount, adjustedArea, edge); } else if (anchor == CategoryAnchor.MIDDLE) { result = getCategoryMiddle(category, categoryCount, adjustedArea, edge); } else if (anchor == CategoryAnchor.END) { result = getCategoryEnd(category, categoryCount, adjustedArea, edge); } return result; }
8
@Test public void testGetPixel() { try { // Boundary test // Top left corner assertEquals(i.getPixel(0, 0, Colour.RED), 136); assertEquals(i.getPixel(0, 0, Colour.GREEN), 146); assertEquals(i.getPixel(0, 0, Colour.BLUE), 149); // Top right corner assertEquals(i.getPixel(0, 3871, Colour.RED), 116); assertEquals(i.getPixel(0, 3871, Colour.GREEN), 122); assertEquals(i.getPixel(0, 3871, Colour.BLUE), 127); // Bottom left corner assertEquals(i.getPixel(2591, 0, Colour.RED), 208); assertEquals(i.getPixel(2591, 0, Colour.GREEN), 216); assertEquals(i.getPixel(2591, 0, Colour.BLUE), 224); // Bottom right corner assertEquals(i.getPixel(2591, 3871, Colour.RED), 123); assertEquals(i.getPixel(2591, 3871, Colour.GREEN), 89); assertEquals(i.getPixel(2591, 3871, Colour.BLUE), 85); } catch (ImageTooSmallException e) { fail("Exception occurred"); } try { // xOffset < 0 assertEquals(i.getPixel(2591, -5, Colour.RED), 208); fail("IllegalArgumentException not triggered"); } catch (IllegalArgumentException e) { } catch (ImageTooSmallException e) { fail("Wrong exception triggered!"); } try { // yOffset < 0 assertEquals(i.getPixel(-5, 100, Colour.RED), 208); fail("IllegalArgumentException not triggered"); } catch (IllegalArgumentException e) { } catch (ImageTooSmallException e) { fail("Wrong exception triggered!"); } try { // xOffset >= 3872 assertEquals(i.getPixel(2591, 4000, Colour.RED), 208); fail("ImageTooSmallException not triggered"); } catch (IllegalArgumentException e) { fail("Wrong exception triggered!"); } catch (ImageTooSmallException e) { } try { // yOffset >= 2592 assertEquals(i.getPixel(2644, 200, Colour.RED), 208); fail("ImageTooSmallException not triggered"); } catch (IllegalArgumentException e) { fail("Wrong exception triggered!"); } catch (ImageTooSmallException e) { } }
9
@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((dataOrcamento == null) ? 0 : dataOrcamento.hashCode()); result = prime * result + id; result = prime * result + pagamento; result = prime * result + ((pessoa == null) ? 0 : pessoa.hashCode()); result = prime * result + ((servLista == null) ? 0 : servLista.hashCode()); result = prime * result + ((validadeOrcamento == null) ? 0 : validadeOrcamento .hashCode()); return result; }
4
public static void xmlToBTX(File fin, File fout) throws XMLStreamException, IOException { XMLInputFactory fact = XMLInputFactory.newFactory(); try (FileReader fr = new FileReader(fin); BTXPusher out = new BTXPusher(fout)) { XMLEventReader in = fact.createXMLEventReader(fr); XMLEvent s; while (!(s = in.nextEvent()).isEndDocument()) { if (!s.isStartDocument()) { if (s.isStartElement()) { StartElement st = (StartElement) s; out.startObject(st.getName().toString()); @SuppressWarnings({"cast", "unchecked"}) Iterator<Attribute> it = (Iterator<Attribute>) st.getAttributes(); while (it.hasNext()) { Attribute at = it.next(); out.addAttribute(at.getName().toString(), at.getValue()); } } else if (s.isEndElement()) { out.endObject(); } else if (s.isCharacters()) { Characters ch = (Characters) s; if (!ch.isWhiteSpace()) { out.startObject("<t"); out.addAttribute("", ch.getData()); out.endObject(); } } } } } }
7
public void playCity() throws InterruptedException{ try { in = new FileInputStream(city); as = new AudioStream(in); ap.player.start(as); } catch(Exception e) { System.out.println("Got an IOException: " + e.getMessage()); e.printStackTrace(); } Thread.sleep(cityLen); }
1
public static void textPack(byte packedData[], String text) { if (text.length() > 80) { text = text.substring(0, 80); } int length = text.length(); int key = 0; int bitPosition = 1 << 3; int srcOffset = 0; packedData[0] = (byte) length; for (; length > srcOffset; srcOffset++) { int textByte = 0xff & text.getBytes()[srcOffset]; int mask = CHAT_MASKS[textByte]; int size = CHAT_BIT_SIZES[textByte]; int destOffset = bitPosition >> 3; int bitOffset = bitPosition & 0x7; key &= (-bitOffset >> 31); bitPosition += size; int byteSize = (((bitOffset + size) - 1) >> 3) + destOffset; bitOffset += 24; packedData[destOffset] = (byte) (key = (key | (mask >>> bitOffset))); if (byteSize > destOffset) { destOffset++; bitOffset -= 8; packedData[destOffset] = (byte) (key = mask >>> bitOffset); if (byteSize > destOffset) { destOffset++; bitOffset -= 8; packedData[destOffset] = (byte) (key = mask >>> bitOffset); if (byteSize > destOffset) { bitOffset -= 8; destOffset++; packedData[destOffset] = (byte) (key = mask >>> bitOffset); if (destOffset < byteSize) { bitOffset -= 8; destOffset++; packedData[destOffset] = (byte) (key = mask << -bitOffset); } } } } } }
6
static void init(){ appPath = (System.getProperty("user.home")); if(isWindows()){ //appPath = appPath + "\\Application Data\\StudyBuddy\\";//Windows uses backslash. Two needed as escape sequence appPath = System.getenv("APPDATA") + "\\StudyBuddy\\"; //Above invalid on non default systems (e.g. non english, vista, etc.) } else{ appPath = appPath + "/.StudyBuddy/";//put back '.' could someone on linux test this? } File folder = new File(appPath); if (!folder.isDirectory()) { //log.print(LogType.Error,"path doesnt exist: "+appPath); //Make directory appPath boolean success = (new File(appPath)).mkdir(); if(!success) log.print(LogType.Error,"StudyBuddy Directory could not be created"); } //else log.print(LogType.Debug,"path exists :)"); propFile = new File(appPath+propertiesFile); if (!propFile.exists()) { //log.print(LogType.Error,"properties files doesnt exist"); //create propertiesFile file with default values as properties try{ propFile.createNewFile(); //log.print(LogType.Debug,"New file created"); setupJavaPropertiesObject(); setDefaults(); } catch(Exception e){ log.print(LogType.Error,"Properties file couldnt be created"); //Throw custom error? } } else { //log.print(LogType.Debug,"Properties file already exists"); setupJavaPropertiesObject(); //if version is different reset defaults. This is as default settings may have changed causing incompatabilites. if(AppDefaults.ver.valueDifferent(getSetting("appVersionLast"))){ setDefaults(); } } }
6
@Override public void mouseExited(MouseEvent e) { if (isDragging) { // Update the UI if (targetNode.isSelected() && !targetNode.isFirstChild() && (componentType == TEXT)) { OutlineLayoutManager layout = targetNode.getTree().getDocument().panel.layout; OutlinerCellRendererImpl renderer = layout.getUIComponent(targetNode.prevSibling()); if (renderer != null) { renderer.button.updateIcon(); } } else { currentRenderer.button.updateIcon(); } // Update targetNode targetNode = null; } }
5
public boolean displayModesMatch(DisplayMode m1, DisplayMode m2){ if(m1.getWidth() != m2.getWidth() || m1.getHeight() != m2.getHeight()){ return false; } if(m1.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI && m2.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI && m1.getBitDepth() != m2.getBitDepth()){ return false; } if(m1.getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN && m2.getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN && m1.getRefreshRate() != m2.getRefreshRate()){ return false; } return true; }
8
public void run () { // se realiza el ciclo del juego en este caso nunca termina while (true) { /* mientras dure el juego, se actualizan posiciones de jugadores se checa si hubo colisiones para desaparecer jugadores o corregir movimientos y se vuelve a pintar todo */ if (bInicio) { if (!bPausa) { actualiza(); checaColision(); } repaint(); } try { // El thread se duerme. Thread.sleep (20); } catch (InterruptedException iexError) { System.out.println("Hubo un error en el juego " + iexError.toString()); } } }
4
public static String convertFloat(float amount, boolean speech) { int num = (int) amount; String start = Integer.toString(num); int remainder = (int) ((amount - num) * 1000); if (start.equals("0")) { start = ""; } else if (remainder > 0) { if (speech) { start += " and "; } else { start += " "; } } if (remainder > 0) { int denominator = 0; int numerator = 0; for (int i : breakdowns) { if (remainder % i == 0) { denominator = 1000 / i; numerator = remainder / i; break; } } if (denominator > 0 && numerator > 0) { if (speech) return start + Integer.toString(numerator) + " " + fraction(denominator); else return start + Integer.toString(numerator) + "/" + Integer.toString(denominator); } else { return Float.toString(amount); } } return start; }
9
public static void writeForALevel(int level) throws Exception { System.out.println(level); BufferedReader reader = new BufferedReader(new FileReader(new File( ConfigReader.getGoranOct2015Dir() + File.separator + "PC_0016 Metagenomics Study Report" + File.separator + "PC_0016 Data" + File.separator + "PC_0016 Seq_data.txt"))); String taxa = "otu"; if( level > 0 ) taxa = NewRDPParserFileLine.TAXA_ARRAY[level]; File outFile = new File( ConfigReader.getGoranOct2015Dir() + File.separator + taxa + "_asColumns.txt"); BufferedWriter writer= new BufferedWriter(new FileWriter(outFile)); HashMap<String, List<Integer>> map = getTaxaMap(level); List<String> keys = new ArrayList<String>( map.keySet()); Collections.sort(keys); String[] sampleNames = reader.readLine().split("\t"); String[] interventionNames = reader.readLine().split("\t"); List<String> namesPlusCategory = new ArrayList<String>(); if( sampleNames.length != interventionNames.length) throw new Exception("No"); for( int x=3; x < sampleNames.length; x++) namesPlusCategory.add(sampleNames[x] +"_" + interventionNames[x]); writer.write("sample"); for(String s : keys) writer.write("\t" + s); writer.write("\n"); for( int x=0; x < namesPlusCategory.size(); x++) { writer.write(namesPlusCategory.get(x)); for(String key : keys) { List<Integer> list = map.get(key); writer.write("\t" + list.get(x)); } writer.write("\n"); } writer.flush(); writer.close(); reader.close(); OtuWrapper wrapper = new OtuWrapper(outFile); File loggedFile = new File( ConfigReader.getGoranOct2015Dir() + File.separator + taxa + "_asColumnsLogNorm.txt"); wrapper.writeNormalizedLoggedDataToFile(loggedFile); }
6
public CommandEditConfig(CreeperWarningMain plugin) { this.plugin = plugin; }
0
public Chance not() { return new Chance(1 - probability); }
0
public boolean loadParameterFromFile(String path) { BufferedReader br; boolean done = false; int counter = 0; String currLine = null; try{ br = new BufferedReader(new FileReader(path)); while((currLine = br.readLine()) != null) { if(counter == 0) { this.jTextField2.setText(currLine); }else if(counter == 1) { this.jTextField1.setText(currLine); }else if(counter == 2) { this.jTextField3.setText(currLine); }else if(counter == 3) { this.jTextField4.setText(currLine); }else if(counter == 4) { this.jTextField5.setText(currLine); }else if(counter == 5) { this.jTextField6.setText(currLine); done = true; }else { break; } counter ++; } }catch(IOException e) { this.guiController.createdPopupDialog("Warning", "Invalid Parameter File!"); } return done; }
8
public void renderSides(){ for(int i = 0; i < worldHeight - 2; i++){ renderTileSize(sideTextures[0], 0, i + 1); } for(int i = 0; i < worldWidth - 2; i++){ renderTileSize(sideTextures[1], i + 1, 0); } for(int i = 0; i < worldHeight - 2; i++){ renderTileSize(sideTextures[2], worldWidth -1, i + 1); } for(int i = 0; i < worldWidth - 2; i++){ renderTileSize(sideTextures[3], i + 1, worldHeight -1); } renderTileSize(sideTextures[4], 0, 0); renderTileSize(sideTextures[5], worldWidth -1, 0); renderTileSize(sideTextures[6], worldWidth -1, worldHeight -1); renderTileSize(sideTextures[7], 0, worldHeight -1); }
4
private void processLoadState() { // loadingStages if (Client.lowMem && loadingStage == 2 && Region.anInt131 != plane) { gameScreenCanvas.initDrawingArea(); aFont_1271.drawANCText(0, "Loading - please wait.", 151, 257); aFont_1271.drawANCText(0xffffff, "Loading - please wait.", 150, 256); gameScreenCanvas.drawGraphics(4, super.graphics, 4); loadingStage = 1; aLong824 = System.currentTimeMillis(); } if (loadingStage == 1) { int j = method54(); if (j != 0 && System.currentTimeMillis() - aLong824 > 0x57e40L) { Signlink.reporterror(myUsername + " glcfb " + aLong1215 + "," + j + "," + Client.lowMem + "," + cacheIndices[0] + "," + onDemandFetcher.getRemaining() + "," + plane + "," + anInt1069 + "," + anInt1070); aLong824 = System.currentTimeMillis(); } } if (loadingStage == 2 && plane != anInt985) { anInt985 = plane; method24(plane); } }
8
@Override public void run() { try { while(connection.isConnected()) { String requestS = ""; BufferedReader reader = new BufferedReader( new InputStreamReader(connection.getInputStream())); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(connection.getOutputStream())); String line = reader.readLine(); while(line != null && line.length() > 0) { requestS += line + "\r\n"; line = reader.readLine(); } Request request = Request.parseRequest(requestS); if(request.type == Request.Type.SETUP) { session = new Session(server.getNewSessionID(), connection.getInetAddress(), request.getPort()); server.addSession(session); } else if(session == null) session = server.getSession(request.session); Response response = session.newRequest(request); writer.write(response.toString()); writer.flush(); if(request.type == Request.Type.TEARDOWN) { server.removeSession(session); connection.close(); } } } catch (IOException e) { e.printStackTrace(); } }
7
@Override public void setDetailedHops(List<Integer> hopPath, AggregatePositioner source) { DefaultListModel model = ((DefaultListModel) getReportHopList().getModel()); model.clear(); if (hopPath == null) ((DefaultListModel) reportHopList.getModel()).addElement("No selection"); else { model.addElement(hopPath.get(0) + HOP_SEPARATOR + hopPath.get(hopPath.size() - 1)); for (Integer value : hopPath) { model.addElement(value); } } }
2
public static int[] getMatchesBetween(Integer team1, Integer team2, String temporada, Connection conexion) throws SQLException{ StringBuilder query = new StringBuilder(); query.append("SELECT Empate, VictoriaLocal, VictoriaVisitante FROM Partidos "); query.append("WHERE Local = "); query.append(team1); query.append(" AND Visitante = "); query.append(team2); query.append(" AND Temporada < \""); query.append(temporada); query.append("\""); Statement st = conexion.createStatement(); ResultSet rs = st.executeQuery(query.toString()); int[] historico = new int[6]; while(rs.next()){ if(rs.getBoolean(1)){ historico[0]+= 1; } if(rs.getBoolean(2)){ historico[1]+= 1; } if(rs.getBoolean(3)){ historico[2]+= 1; } } st.close(); rs.close(); query.delete(0, query.length()); query.append("SELECT Empate, VictoriaLocal, VictoriaVisitante FROM Partidos "); query.append("WHERE Local = "); query.append(team2); query.append(" AND Visitante = "); query.append(team1); query.append(" AND Temporada < \""); query.append(temporada); query.append("\""); st = conexion.createStatement(); rs = st.executeQuery(query.toString()); while(rs.next()){ if(rs.getBoolean(1)){ historico[3]+= 1; } if(rs.getBoolean(2)){ historico[4]+= 1; } if(rs.getBoolean(3)){ historico[5]+= 1; } } st.close(); rs.close(); return historico; }
8
public static String[] splitMoveText(StringBuffer movetext) { while (Character.isWhitespace(movetext.charAt(0))) { movetext.deleteCharAt(0); } List tokens = new LinkedList(); String lastToken = ""; while (movetext.length() > 0) { while (Character.isDigit(movetext.charAt(0))) { movetext.deleteCharAt(0); } assert (movetext.charAt(0) == '.'); movetext.deleteCharAt(0); while (Character.isWhitespace(movetext.charAt(0))) { movetext.deleteCharAt(0); } int c = 1; while (c < movetext.length() && !(Character.isWhitespace(movetext.charAt(c - 1)) && Character.isDigit(movetext .charAt(c)))) { c++; } lastToken = movetext.substring(0, c - 1); tokens.add(lastToken); movetext.delete(0, c); } return (String[]) tokens.toArray(new String[0]); }
7
public void cpuTurn() { AbstractPlay play=black.nextPlay(); play.execute(); log.setMessage(play.toString()); if(play instanceof Capture){ turnChanger.eatIncrement(); FactoryOfPlays factory = new FactoryOfCapturingsForPiece(play.getDestination(), board); while (!factory.isEmpty()){ play = black.nextCapture(play.getDestination()); play.execute(); factory = new FactoryOfCapturingsForPiece(play.getDestination(), board); log.setMessage(play.toString()); turnChanger.eatIncrement(); } } }
2
@Override public List<Course> getCourses(int userId) throws SQLException { List<Course> courseList = new ArrayList<>(); Connection connect = null; PreparedStatement statement = null; try { Class.forName(Params.bundle.getString("urlDriver")); connect = DriverManager.getConnection(Params.bundle.getString("urlDB"), Params.bundle.getString("userDB"), Params.bundle.getString("passwordDB")); String getTeacherId = "select teacher.id from teacher " + "where teacher.user_id = ?"; statement = connect.prepareStatement(getTeacherId); statement.setInt(1, userId); ResultSet teacherIdSet = statement.executeQuery(); teacherIdSet.next(); int teacherId = teacherIdSet.getInt("teacher.id"); String selectCourse = "select general_course_catalog.title, course_catalog.id from course_catalog " + "inner join general_course_catalog on course_catalog.general_course_catalog_id=general_course_catalog.id " + "where course_catalog.teacher_id = ?"; statement = connect.prepareStatement(selectCourse); statement.setInt(1, teacherId); ResultSet resultMark = statement.executeQuery(); while (resultMark.next()){ int course_id = resultMark.getInt("course_catalog.id"); String title = resultMark.getString("general_course_catalog.title"); Course course = new Course(); course.setId(course_id); course.setTitle(title); courseList.add(course); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); }finally { if(connect != null) connect.close(); if(statement != null) statement.close(); return courseList; } }
5
private SplayTreeNode zagZag(SplayTreeNode node) { SplayTreeNode k1 = new SplayTreeNode(node.parent.parent); SplayTreeNode k1Parent = k1.parent; SplayTreeNode a = new SplayTreeNode(node.parent.parent.left); if (a.isNull()) a.parent = k1; SplayTreeNode k2 = new SplayTreeNode(node.parent); SplayTreeNode b = new SplayTreeNode(node.parent.left); if (b.isNull()) b.parent = k2; SplayTreeNode k3 = new SplayTreeNode(node); SplayTreeNode c = new SplayTreeNode(node.left); SplayTreeNode d = new SplayTreeNode(node.right); if (c.isNull()) c.parent = k3; if (d.isNull()) d.parent = k3; k1.left = a; k1.right = b; k2.left = k1; k2.right = c; k3.left = k2; k3.right = d; k3.parent = k1Parent; k1.parent = k2; k2.parent = k3; b.parent = k1; c.parent = k2; node = k3; if (node.parent != null) { node.parent.right = node; } return node; }
5
@Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Austritt)) { return false; } Austritt other = (Austritt) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; }
5
public final Collection getCollection(Identifier ident) { if (ident instanceof PackageIdentifier) return packs; else if (ident instanceof ClassIdentifier) return clazzes; else if (ident instanceof MethodIdentifier) return methods; else if (ident instanceof FieldIdentifier) return fields; else if (ident instanceof LocalIdentifier) return locals; else throw new IllegalArgumentException(ident.getClass().getName()); }
5
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(LatihanGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(LatihanGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(LatihanGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(LatihanGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new LatihanGui().setVisible(true); } }); }
6
@Override public Ship clone() { // Create new hashmap for the new nodes Map<Coordinates, Node> nodes = new HashMap<Coordinates, Node>(); // Put transfer each node to the new hashmap for (Node n : nodeMap.values()) { Coordinates coords = n.getCoordinates(); nodes.put(coords, new Node(coords.row, coords.col)); } // New Edge Map Map<Set<Node>, Edge> edges = new HashMap<Set<Node>, Edge>(); // Transfer all the edges to the new ship for (Edge e : edgeMap.values()) { Set<Node> oldNodes = e.getAdjacent(); Iterator<Node> I = oldNodes.iterator(); Node nodeOne = I.next(); Node nodeTwo = I.next(); Node newNodeOne = nodes.get(new Coordinates(nodeOne.getCoordinates().row, nodeOne.getCoordinates().col)); Node newNodeTwo = nodes.get(new Coordinates(nodeTwo.getCoordinates().row, nodeTwo.getCoordinates().col)); Set<Node> newNodes = new HashSet<Node>(); newNodes.add(newNodeOne); newNodes.add(newNodeTwo); Edge newEdge = new Edge(e.getEdgeState(), newNodeOne, newNodeTwo); edges.put(newNodes, newEdge); newNodeOne.addEdge(newEdge); newNodeTwo.addEdge(newEdge); } return new Ship(nodes, edges, alienNode, predatorNode); }
2
public static void modifierReponse(Reponse reponse, String nouveauMessage, Utilisateur utilisateur) throws ChampInvalideException, ChampVideException { if (utilisateur == null || (!utilisateur.equals(reponse.getAuteur()) && utilisateur.getRole().getValeur() < reponse.getSujet().getReponseRoleMinimum().getValeur())) throw new InterditException("Vous n'avez pas les droits requis pour modifier cette réponse"); EntityTransaction transaction = SujetRepo.get().transaction(); String ancienMessage = reponse.getMessage(); try { transaction.begin(); reponse.setMessage(nouveauMessage); validerReponse(reponse); ReponseRepo.get().mettreAJour(reponse); transaction.commit(); } catch(Exception e) { if (transaction.isActive()) transaction.rollback(); reponse.setMessage(ancienMessage); throw e; } }
5
public int search(int[] A, int target) { int left = 0; int right = A.length - 1; while (left <= right) { int mid = (left + right) / 2; if (A[mid] == target) { return mid; } if (A[mid] >= A[left]) { if (A[left] <= target && target <= A[mid]) { right = mid - 1; } else { left = mid + 1; } } else { if (A[mid] >= target || target >= A[left]) { right = mid - 1; } else { left = mid + 1; } } } return -1; }
7
static int process(String line) { if(line == null || line.trim().length() == 0) return 0; int n = Integer.parseInt(line.trim()); String[] p = readLine().trim().split(" "); Map<String, Long> mp = new HashMap<>(); for(String str : p) { mp.put(str, (long) 0); } for(int i = 0; i < n; i++) { String[] splts = readLine().trim().split(" "); String k= splts[0].trim(); long amt = Long.parseLong(splts[1].trim()); int cnt = Integer.parseInt(splts[2]); long keep = -amt, dist = 0; if(cnt > 0) { keep += amt % cnt; dist = amt / cnt; } else { keep = 0; } for(int j = 3; j < (3 + cnt); j++) { String s = splts[j].trim(); mp.put(s, mp.get(s) + dist); } mp.put(k, mp.get(k) + keep); } if(notfirst) System.out.println(); else notfirst = true; for(String s : p) { System.out.println(s + " " + mp.get(s)); } return 1; }
8
private void loadAnalyzers() { // Lista cu analizatoarele disponibile aList = new ArrayList<Analyzer>(); // Deschide directorul xml_schema. File directory = new File(Config.exec_schemas); // Ia fisierele din directorul xml_schema. File[] files = directory.listFiles(); // Parseaza fiecare fisier. for (File file2 : files) { if (file2.isFile()) { String file; file = file2.getAbsolutePath(); Analyzer a = this.getAnalyzer(file); if (a != null) { aList.add(a); } } } // Verifica daca exista analizatoare. if (aList.size() == 0) { ErrorMessage.show("Nu exista analizatoare disponibile!"); } }
4
public void setName(String name) { this.name = name; setDirty(); }
0
public static boolean CheckGetCommandList(String path){ boolean result = false; ArrayList<Commands> inputCommands; inputCommands = FileReader.getCommandList(path); for (Commands print : inputCommands) { if(print == null){ result = true; break; } if(print.getCommand() == null || print.getPath() == null){ result = true; break; } } return !result; }
4
public void onKeyEvent() { if (Keyboard.getEventKeyState()) { if (Keyboard.getEventKey() == Keyboard.KEY_LEFT) { this.position.setPositionX(this.position.getPositionX() - 1); } if (Keyboard.getEventKey() == Keyboard.KEY_RIGHT) { this.position.setPositionX(this.position.getPositionX() + 1); } if (Keyboard.getEventKey() == Keyboard.KEY_UP) { this.position.setPositionY(this.position.getPositionY() + 1); } if (Keyboard.getEventKey() == Keyboard.KEY_DOWN) { this.position.setPositionY(this.position.getPositionY() - 1); } } }
5
public Conexion(){ try{ System.out.println("Cargando conexion..."); Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); System.out.println("Cargando driver..."); cnx = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=dbRestaurante2012442", "BP", "123"); // cnx = DriverManager.getConnection("jdbc:sqlserver://192.168.107.112:1433;databaseName=dbRestaurante2012442", "BP", "123"); System.out.println("Cargando base de datos..."); estado = cnx.createStatement(); System.out.println("Creando estado.."); }catch(ClassNotFoundException cnfe){ cnfe.printStackTrace(); System.out.println("error "+cnfe); }catch(SQLException sqle){ sqle.printStackTrace(); System.out.println("error "+sqle); } }
2
public String[] obtenerRespuestasCorrectas(int tamaño){ String csvFile = "dataset/diabetes_prueba_resultados.csv"; BufferedReader br = null; String line = ""; String cvsSplitBy = ","; String respuestas [] = new String [tamaño]; int contador = 0; try { br = new BufferedReader(new FileReader(csvFile)); while ((line = br.readLine()) != null) { String[] patron = line.split(cvsSplitBy); respuestas[contador] = patron[8]; contador++; } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (IndexOutOfBoundsException e) { System.out.println("Error accediendo al csv"); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } return respuestas; }
6
public static ServiceManager getServices() { return _services; }
0
public <X> void processAnnotatedType(@Observes ProcessAnnotatedType<X> event, final BeanManager beanManager) { final AnnotatedType<X> type = event.getAnnotatedType(); for (AnnotatedMethod<?> method : type.getMethods()) { for (final AnnotatedParameter<?> param : method.getParameters()) { if (param.isAnnotationPresent(Observes.class) && param.isAnnotationPresent(Async.class)) { asyncObservers.add(ObserverMethodHolder.create(this.pool, beanManager, type, method, param)); } } } }
6
public static void main(String[] args) { // метод мэйн должен описывать общий сценарий и быть максимально коротким Game game; try { if (args.length == 0) { game = new Game(); } else { game = new Game(args); } // game = args.length > 0 ? new Game(args) : new Game(); // вариант через тернарную операцию if (game.register()) { // регистрация пользователя game.getGamerList(); // получение и отображение спика свободных игроков game.startGame(); // старт игры /* if (game.prepareGame()) { // соглашение с игроком game.startGame(); // старт игры } if (game.waitInvait()) { // режим ожидания приглашения или выход из игры return; }*/ System.out.println(game.gamer.getNick()); } } catch (IOException | GameException | IllegalAccessException e) { System.err.println("Error 1#" + e.getMessage()); } catch (ClassNotFoundException e) { e.printStackTrace(); } System.out.println("Ok"); }
4
@Override public String getDescription(Hero hero) { int bDmg = SkillConfigManager.getUseSetting( hero, this,"BaseTickDamage", 0, false); float bMulti = SkillConfigManager.getUseSetting( hero, this,"LevelMultiplier", 0, false); long duration = SkillConfigManager.getUseSetting( hero, this,Setting.DURATION, 12000, false); int damage = (int) (bMulti <= 0L ? bDmg : bDmg + bMulti * hero.getLevel()); String newDmg = damage > 0 ? "Deals " + damage + " over " + duration/1000D + " seconds" : ""; String base = String.format( "Encapsulate your target in ice for %s seconds. ", duration / 1000D ); StringBuilder description = new StringBuilder( base + newDmg ); //Additional descriptive-ness of skill settings int initCD = SkillConfigManager.getUseSetting(hero, this, Setting.COOLDOWN.node(), 0, false); int redCD = SkillConfigManager.getUseSetting(hero, this, Setting.COOLDOWN_REDUCE.node(), 0, false) * hero.getSkillLevel(this); int CD = (initCD - redCD) / 1000; if (CD > 0) { description.append( " CD:"+ CD + "s" ); } int initM = SkillConfigManager.getUseSetting(hero, this, Setting.MANA.node(), 0, false); int redM = SkillConfigManager.getUseSetting(hero, this, Setting.MANA_REDUCE.node(), 0, false)* hero.getSkillLevel(this); int manaUse = initM - redM; if (manaUse > 0) { description.append(" M:"+manaUse); } int initHP = SkillConfigManager.getUseSetting(hero, this, Setting.HEALTH_COST, 0, false); int redHP = SkillConfigManager.getUseSetting(hero, this, Setting.HEALTH_COST_REDUCE, 0, true) * hero.getSkillLevel(this); int HPCost = initHP - redHP; if (HPCost > 0) { description.append(" HP:"+HPCost); } int initF = SkillConfigManager.getUseSetting(hero, this, Setting.STAMINA.node(), 0, false); int redF = SkillConfigManager.getUseSetting(hero, this, Setting.STAMINA_REDUCE.node(), 0, false) * hero.getSkillLevel(this); int foodCost = initF - redF; if (foodCost > 0) { description.append(" FP:"+foodCost); } int delay = SkillConfigManager.getUseSetting(hero, this, Setting.DELAY.node(), 0, false) / 1000; if (delay > 0) { description.append(" W:"+delay); } int exp = SkillConfigManager.getUseSetting(hero, this, Setting.EXP.node(), 0, false); if (exp > 0) { description.append(" XP:"+exp); } return description.toString(); }
8
@Override public void doAction(Player player, Grid grid) throws InvalidActionException { if (player.getRemainingTurns() <= 0) throw new InvalidActionException("The player has no turns left!"); Position currentPos = player.getPosition(); Position newPos = new Position(currentPos.getxCoordinate() + 1, currentPos.getyCoordinate()); if (!canMoveToPosition(player, grid, newPos)) throw new InvalidActionException("The player can't move to the desired position!"); player.setPosition(newPos); player.getLightTrail().addPosition(currentPos); player.decrementTurn(); }
2
@Override public void actionPerformed(ActionEvent arg0) { if((JButton)arg0.getSource() == btnEditThisPage) { if(editMode) editOff(); else editOn(); } else if((JButton)arg0.getSource() == btnBack) { overlord.cl.show(overlord.getContentPane(), "resultsPage"); } else if((JButton)arg0.getSource() == btnChanges) { if(JOptionPane.showConfirmDialog( this, "Are you sure you want to commit your changes?", "Edit Confirmation", JOptionPane.OK_CANCEL_OPTION ) == 0) { System.out.println("OK Button Clicked!"); if(newPerson) addNewPerson(); else commitChanges(); } else System.out.println("Cancel Button Clicked!"); } else if((JButton)arg0.getSource() == btnDeleteThisPerson) { deletePerson(fieldNum(txt_ID)); } else if((JButton)arg0.getSource() == btnVisualize) { Visualizer vis = new Visualizer(); vis.runVisualizer(fieldNum(txt_ID),2); } }
8
private void incDec16bit(int rTo, boolean inc) { rLoadedFromAddress[rTo] = rLoadedFromAddress[rTo+1] = -1; if(rMask[rTo] == 0xFF && rMask[rTo+1] == 0xFF) { if(inc) r[rTo+1]++; else r[rTo+1]--; if(r[rTo+1] >= 0x100) { r[rTo+1] -= 0x100; r[rTo] = (r[rTo]+1) & 0xFF; } if(r[rTo+1] < 0x0) { r[rTo+1] += 0x100; r[rTo] = (r[rTo]+0xFF) & 0xFF; } } else { rMask[rTo] = rMask[rTo+1] = 0; } }
5
public void deletContact(String first, String last){ for(Contacts aContact:contacts){ if (first.equals(aContact.firstName) && last.equals(aContact.lastName)){ System.out.print(last+","+first+" has been removed!\n"); } else{ System.out.println("No record found."); } } }
3
@Override public String getName() { return "user"; }
0
@Override public void handle(Message<?> event) { Object body = event.body(); javax.jms.Message jmsMessage = null; String contentType = null; if (body instanceof JsonObject ) { try { jmsMessage = session.createTextMessage(body.toString()); contentType = "application/json"; } catch (JMSException e) { e.printStackTrace(); } } else if ( body instanceof String ) { try { jmsMessage = session.createTextMessage(body.toString()); contentType = "text/plain"; } catch (JMSException e) { e.printStackTrace(); } } else if (body instanceof Buffer) { try { jmsMessage = session.createBytesMessage(); contentType = "application/octet-stream"; ((BytesMessage) jmsMessage).writeBytes(((Buffer) body).getBytes()); } catch (JMSException e) { e.printStackTrace(); } } if (jmsMessage != null) { try { jmsMessage.setStringProperty("Content-Type", contentType ); this.producer.send(jmsMessage); } catch (JMSException e) { e.printStackTrace(); } } }
9
static final int method3405(int i, boolean bool) { anInt9765++; if (Class348_Sub1.anIntArray6547 == null) return 0; if (!bool && Class199.aClass352Array2636 != null) return Class348_Sub1.anIntArray6547.length * 2; int i_1_ = 0; if (i != 2012104999) method3405(118, false); for (int i_2_ = 0; Class348_Sub1.anIntArray6547.length > i_2_; i_2_++) { int i_3_ = Class348_Sub1.anIntArray6547[i_2_]; if (Class39.spriteIndexLoader.getArchiveLoaded(i_3_)) i_1_++; if (s.fontIndexLoader.getArchiveLoaded(i_3_)) i_1_++; } return i_1_; }
7
public CreatureTemplateDialog() { setTitle("Creature Template Editor - MSB"); setBounds(100, 100, 294, 110); getContentPane().setLayout(new BorderLayout()); contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5)); getContentPane().add(contentPanel, BorderLayout.CENTER); GridBagLayout gbl_contentPanel = new GridBagLayout(); gbl_contentPanel.columnWidths = new int[]{0, 0, 0}; gbl_contentPanel.rowHeights = new int[]{33, 0}; gbl_contentPanel.columnWeights = new double[]{0.0, 1.0, Double.MIN_VALUE}; gbl_contentPanel.rowWeights = new double[]{0.0, Double.MIN_VALUE}; contentPanel.setLayout(gbl_contentPanel); { JLabel lblCreatureTemplate = new JLabel("Creature Template"); GridBagConstraints gbc_lblCreatureTemplate = new GridBagConstraints(); gbc_lblCreatureTemplate.insets = new Insets(0, 0, 0, 5); gbc_lblCreatureTemplate.anchor = GridBagConstraints.EAST; gbc_lblCreatureTemplate.gridx = 0; gbc_lblCreatureTemplate.gridy = 0; contentPanel.add(lblCreatureTemplate, gbc_lblCreatureTemplate); } { tbCreatureTempName = new JTextField(); GridBagConstraints gbc_tbCreatureTempName = new GridBagConstraints(); gbc_tbCreatureTempName.fill = GridBagConstraints.HORIZONTAL; gbc_tbCreatureTempName.gridx = 1; gbc_tbCreatureTempName.gridy = 0; contentPanel.add(tbCreatureTempName, gbc_tbCreatureTempName); tbCreatureTempName.setColumns(10); } { JPanel buttonPane = new JPanel(); buttonPane.setLayout(new FlowLayout(FlowLayout.CENTER)); getContentPane().add(buttonPane, BorderLayout.SOUTH); { JButton okButton = new JButton("OK"); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { String template = tbCreatureTempName.getText(); if (!template.startsWith("object/mobile/") || !template.endsWith(".iff")) { Helpers.showMessageBox(contentPanel, template + " is an invalid weapon template."); return; } if (mainWnd.getCreatureTemps() != null && mainWnd.getCreatureTemps().size() == 0) { DefaultListModel<String> model = new DefaultListModel<String>(); model.addElement(template); mainWnd.setCreatureTemps(model); mainWnd.getListWeaponTemps().setModel(model); } else if (mainWnd.getCreatureTemps().contains(template)) { // Nothing changed, nothing needs to be done. } else { mainWnd.getCreatureTemps().addElement(template); } dispose(); } }); okButton.setActionCommand("OK"); buttonPane.add(okButton); getRootPane().setDefaultButton(okButton); } { JButton cancelButton = new JButton("Cancel"); cancelButton.setActionCommand("Cancel"); buttonPane.add(cancelButton); } } }
5
public void start() { cbTimer.start(new Callback() { double startTime; int tick=0; @Override public void cb() { if (tick==0) startTime=System.nanoTime(); tick++; animationFrame.setAnimationTime((System.nanoTime()-startTime)/1000000); animationFrame.animation(canvas); } }); }
1
private Message queryFromString(String query_line) throws TextParseException, NameTooLongException { String[] tokens = query_line.split("[ \t]+"); Name qname = null; int qtype = -1; int qclass = -1; if (tokens.length < 1) return null; qname = Name.fromString(tokens[0]); if (!qname.isAbsolute()) { qname = Name.concatenate(qname, Name.root); } for (int i = 1; i < tokens.length; i++) { if (tokens[i].startsWith("+")) { // For now, we ignore flags as uninteresting // All queries will get the DO bit anyway continue; } int type = Type.value(tokens[i]); if (type > 0) { qtype = type; continue; } int cls = DClass.value(tokens[i]); if (cls > 0) { qclass = cls; continue; } } if (qtype < 0) { qtype = Type.A; } if (qclass < 0) { qclass = DClass.IN; } Message query = Message.newQuery(Record.newRecord(qname, qtype, qclass)); return query; }
8
public static void findPotentials(String data_file, int iterations) { LoopMRFPotentials p = new LoopMRFPotentials(data_file); LoopyBP lbp = new LoopyBP(p, iterations); for(int i=1; i<=p.loopLength(); i++) { double[] marginal = lbp.marginalProbability(i); if(marginal.length-1 != p.numXValues()) // take off 1 for 0 index which is not used throw new RuntimeException("length of probability distribution is incorrect: " + marginal.length); System.out.println("marginal probability distribution for node " + i + " is:"); double sum = 0.0; for(int k=1; k<=p.numXValues(); k++) { if(marginal[k] < 0.0 || marginal[k] > 1.0) throw new RuntimeException("illegal probability for x_" + i); System.out.println("\tP(x = " + k + ") = " + marginal[k]); sum += marginal[k]; } double err = 1e-5; if(sum < 1.0-err || sum > 1.0+err) throw new RuntimeException("marginal probability distribution for x_" + i + " doesn't sum to 1"); } }
7
private static boolean hasExactly9Digits(int i, int j){ List<Character> results = new ArrayList<Character>(); for(char c : Integer.toString(i).toCharArray()){ if (results.contains(c) || c == '0') return false; results.add(c); } for(char c : Integer.toString(j).toCharArray()){ if (results.contains(c) || c == '0') return false; results.add(c); } for(char c : Integer.toString(i*j).toCharArray()){ if (results.contains(c) || c == '0') return false; results.add(c); } return results.size()==9; }
9
@Override public int attack(NPC npc, Entity target) { final NPCCombatDefinitions defs = npc.getCombatDefinitions(); int distanceX = target.getX() - npc.getX(); int distanceY = target.getY() - npc.getY(); boolean distant = false; int size = npc.getSize(); Familiar familiar = (Familiar) npc; boolean usingSpecial = familiar.hasSpecialOn(); int damage = 0; if (distanceX > size || distanceX < -1 || distanceY > size || distanceY < -1) distant = true; if (usingSpecial) {// priority over regular attack npc.setNextAnimation(new Animation(8190)); target.setNextGraphics(new Graphics(1449)); if (distant) {// range hit delayHit( npc, 2, target, getRangeHit( npc, getRandomMaxHit(npc, 244, NPCCombatDefinitions.RANGE, target)), getRangeHit( npc, getRandomMaxHit(npc, 244, NPCCombatDefinitions.RANGE, target)), getRangeHit( npc, getRandomMaxHit(npc, 244, NPCCombatDefinitions.RANGE, target)), getRangeHit( npc, getRandomMaxHit(npc, 244, NPCCombatDefinitions.RANGE, target))); } else {// melee hit delayHit( npc, 1, target, getMeleeHit( npc, getRandomMaxHit(npc, 244, NPCCombatDefinitions.MELEE, target)), getMeleeHit( npc, getRandomMaxHit(npc, 244, NPCCombatDefinitions.MELEE, target)), getMeleeHit( npc, getRandomMaxHit(npc, 244, NPCCombatDefinitions.MELEE, target)), getMeleeHit( npc, getRandomMaxHit(npc, 244, NPCCombatDefinitions.MELEE, target))); } } else { if (distant) { int attackStage = Utils.getRandom(1);// 2 switch (attackStage) { case 0:// magic damage = getRandomMaxHit(npc, 255, NPCCombatDefinitions.MAGE, target); npc.setNextAnimation(new Animation(7694)); World.sendProjectile(npc, target, 1451, 34, 16, 30, 35, 16, 0); delayHit(npc, 2, target, getMagicHit(npc, damage)); break; case 1:// range damage = getRandomMaxHit(npc, 244, NPCCombatDefinitions.RANGE, target); npc.setNextAnimation(new Animation(8190)); World.sendProjectile(npc, target, 1445, 34, 16, 30, 35, 16, 0); delayHit(npc, 2, target, getRangeHit(npc, damage)); break; } } else {// melee damage = getRandomMaxHit(npc, 244, NPCCombatDefinitions.MELEE, target); npc.setNextAnimation(new Animation(8183)); delayHit(npc, 1, target, getMeleeHit(npc, damage)); } } return defs.getAttackDelay(); }
9
public WorldTest() { }
0
public void next(int width, int height) { x += incX; y += incY; float random = (float)Math.random(); // collision with right side of screen if (x + textWidth > width) { x = width - textWidth; incX = random * -width / 16 - 1; fontFace = 0; fontSize = 125; fillColor = SWT.COLOR_DARK_BLUE; foreGrdColor = SWT.COLOR_YELLOW; fontStyle = SWT.ITALIC; } // collision with left side of screen if (x < 0) { x = 0; incX = random * width / 16 + 1; fontFace = 1; fontSize = 80; fillColor = SWT.COLOR_DARK_MAGENTA; foreGrdColor = SWT.COLOR_CYAN; fontStyle = SWT.NONE; } // collision with bottom side of screen if (y + textHeight > height) { y = (height - textHeight)- 2; incY = random * -height / 16 - 1; fontFace = 2; fontSize = 100; fillColor = SWT.COLOR_YELLOW; foreGrdColor = SWT.COLOR_BLACK; fontStyle = SWT.BOLD; } // collision with top side of screen if (y < 0) { y = 0; incY = random * height / 16 + 1; fontFace = 3; fontSize = 120; fillColor = SWT.COLOR_GREEN; foreGrdColor = SWT.COLOR_GRAY; fontStyle = SWT.NONE; } }
4
public boolean intersectsAbove(RPChromosomeRegion testRegion) { // Only need to test if some part of this region is above and some within test region. if (endChromID > testRegion.endChromID || (endChromID == testRegion.endChromID && endBase > testRegion.endBase)) { if (startChromID < testRegion.endChromID || (startChromID == testRegion.endChromID && startBase < testRegion.endBase)) return true; else return false; } else return false; }
6
public Location getLocation() { return location; }
0
public Coordinate fromCartesian(Vector2D point) { int n = refPolygon.count(); Coordinate coordinate = new Coordinate(n); Vector2D[] si = new Vector2D[n]; double[] Ai = new double[n]; double[] Di = new double[n]; double[] ri = new double[n]; for (int i = 0; i < n; i++) si[i] = (refPolygon.get(i).minus(point)); for (int i = 0; i < n; i++) { int next = (i + 1) % n; ri[i] = (si[i].length()); Ai[i] = (si[i].crossLength(si[next]) * 0.5); Di[i] = (si[i].dot(si[next])); if (ri[i] == 0.0) { coordinate.setCoefficient(i, 1.0); return coordinate; } if (Ai[i] == 0.0 && Di[i] < 0) { ri[next] = si[next].length(); coordinate.setCoefficient(i, ri[next] / (ri[i] + ri[next])); coordinate.setCoefficient(next, ri[i] / (ri[i] + ri[next])); return coordinate; } } double W = 0; for (int i = 0; i < n; i++) { double w = 0; int prev = (i + n - 1) % n; int next = (i + 1) % n; if (Ai[prev] != 0.0) w = w + (ri[prev] - Di[prev] / ri[i]) / Ai[prev]; if (Ai[i] != 0.0) w = w + (ri[next] - Di[i] / ri[i]) / Ai[i]; coordinate.setCoefficient(i, w); W = W + w; } for (int i = 0; i < n; i++) { coordinate.setCoefficient(i, coordinate.getCoefficient(i) / W); } return coordinate; }
9
public static void main(String[] args) { BasicConfigurator.configure(); Logger.getRootLogger().setLevel(Level.INFO); try { listAllClasses(); start(); } catch (BindException e) { try { CloseableHttpClient httpclient = HttpClients.createDefault(); URI uri = new URIBuilder().setScheme("http").setHost("127.0.0.1:8080") .setPath("/control/shutdown/" + SECURITY_TOKEN).build(); HttpGet httpget = new HttpGet(uri); httpclient.execute(httpget); } catch (HttpHostConnectException e1) { try { start(); } catch (Exception e2) { e2.printStackTrace(); } } catch (URISyntaxException | IOException e1) { e1.printStackTrace(); } catch (Exception e1) { e1.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); } }
6
public static void main(String[] args) { // Nested "if" Statements String gender = "female"; int age = 43; if (gender.equalsIgnoreCase("male")) { if (age > 30) { System.out.println("You are a male over the age of 30"); } else { System.out.println("You are a male under the age of 30"); } } else { if (age > 30) { System.out.println("You are a female over the age of 30"); } else { System.out.println("You are a female under the age of 30"); } } }
3
public static void main(String[] args){ Scanner in = new Scanner(System.in); int sit=0, stand=0; int n = in.nextInt(); char[] text = in.next().toCharArray(); for(int i=0;i<text.length;i++){ if(text[i]=='x') sit++; else stand++; } if(sit-stand>0){ int diff = (sit-stand)/2; for(int i=0;i<text.length;i++){ if(diff==0) break; if(text[i]=='x'){ text[i]='X'; diff--; } } } else { int diff = (stand-sit)/2; for(int i=0;i<text.length;i++){ if(diff==0) break; if(text[i]=='X'){ text[i]='x'; diff--; } } } System.out.println(Math.abs(sit-stand)/2); System.out.println(text); }
9
@Override public void setUnixPermissions(String path, UnixPermissions perms) throws PathNotFoundException, AccessDeniedException, UnsupportedFeatureException { if (hardlinks) { //Get hard link paths String[] hardlinks = getHardLinks(path); if (hardlinks.length > 0) path = hardlinks[0]; } if (unixPermissions) { String[] lines = FileSystemUtils.readLines(attributeFs, getPermissionsPath(path), new String[4]); if (lines[0] == null) { if (!innerFs.pathExists(path)) throw new PathNotFoundException(path); } lines[0] = String.valueOf(perms.getPermissions()); lines[1] = String.valueOf(perms.getUid()); lines[2] = String.valueOf(perms.getGid()); if (lines[3] == null) lines[3] = "0"; try { FileSystemUtils.writeLines(attributeFs, getPermissionsPath(path), lines); } catch (NotAFileException e) { e.printStackTrace(); } catch (DriveFullException e) { e.printStackTrace(); } } else innerFs.setUnixPermissions(path, perms); }
8
public Match findId(Match m) { Match found = null; PreparedStatement pst = null; ResultSet rs = null; try { pst=this.connect().prepareStatement("select * from Matches where equipea=? and equipeb=? and scorea=? and scoreb=?"); pst.setString(1, m.getEquipeA()); pst.setString(2, m.getEquipeB()); pst.setInt(3, m.getScoreA()); pst.setInt(4, m.getScoreB()); rs=pst.executeQuery(); System.out.println("recherche individuelle réussie"); if (rs.next()) { found = new Match(rs.getInt("id"), rs.getString("equipeA"), rs.getString("equipeB"),rs.getInt("scoreA"), rs.getInt("scoreB"), rs.getDate("datematch")); } } catch (SQLException ex) { Logger.getLogger(MatchDao.class.getName()).log(Level.SEVERE, "recherche individuelle echoué", ex); }finally{ try { if (rs != null) rs.close(); } catch (SQLException ex) { Logger.getLogger(MatchDao.class.getName()).log(Level.SEVERE, "liberation result set echoué", ex); } try { if (pst != null) pst.close(); } catch (SQLException ex) { Logger.getLogger(MatchDao.class.getName()).log(Level.SEVERE, "liberation prepared statement echoué", ex); } } return found; }
6
public static void walkDefmacroTree(Cons tree) { { Stella_Object name = tree.rest.value; { PropertyList self000 = PropertyList.newPropertyList(); self000.thePlist = Cons.extractOptions(tree, null); { PropertyList options = self000; MethodSlot method = null; if (Stella_Object.consP(name)) { { Object old$PrintreadablyP$000 = Stella.$PRINTREADABLYp$.get(); try { Native.setBooleanSpecial(Stella.$PRINTREADABLYp$, true); Stella.signalTranslationError(); if (!(Stella.suppressWarningsP())) { Stella.printErrorContext(">> ERROR: ", Stella.STANDARD_ERROR); { Stella.STANDARD_ERROR.nativeStream.println(); Stella.STANDARD_ERROR.nativeStream.println(" Macro `" + ((Cons)(name)).value + "' contains return type specification."); } ; } } finally { Stella.$PRINTREADABLYp$.set(old$PrintreadablyP$000); } } return; } if (!(Stella_Object.symbolP(name))) { { Object old$PrintreadablyP$001 = Stella.$PRINTREADABLYp$.get(); try { Native.setBooleanSpecial(Stella.$PRINTREADABLYp$, true); Stella.signalTranslationError(); if (!(Stella.suppressWarningsP())) { Stella.printErrorContext(">> ERROR: ", Stella.STANDARD_ERROR); { Stella.STANDARD_ERROR.nativeStream.println(); Stella.STANDARD_ERROR.nativeStream.println(" Illegal macro name: `" + Stella_Object.deUglifyParseTree(name) + "'."); } ; } } finally { Stella.$PRINTREADABLYp$.set(old$PrintreadablyP$001); } } return; } tree.firstSetter(Stella.SYM_STELLA_DEFUN); options.insertAt(Stella.KWD_MACROp, Stella.SYM_STELLA_TRUE); options.insertAt(Stella.KWD_TYPE, Stella.SYM_STELLA_OBJECT); tree.rest.rest.rest = options.thePlist.concatenate(tree.rest.rest.rest, Stella.NIL); Cons.walkDefmethodTree(tree); if (((TranslationUnit)(Stella.$CURRENTTRANSLATIONUNIT$.get())) != null) { method = ((MethodSlot)(((TranslationUnit)(Stella.$CURRENTTRANSLATIONUNIT$.get())).theObject)); if (method.methodArgumentCount() > 5) { { Object old$PrintreadablyP$002 = Stella.$PRINTREADABLYp$.get(); try { Native.setBooleanSpecial(Stella.$PRINTREADABLYp$, true); Stella.signalTranslationError(); if (!(Stella.suppressWarningsP())) { Stella.printErrorContext(">> ERROR: ", Stella.STANDARD_ERROR); { Stella.STANDARD_ERROR.nativeStream.println(); Stella.STANDARD_ERROR.nativeStream.println(" Too many arguments in macro definition, maximum is 5."); } ; } } finally { Stella.$PRINTREADABLYp$.set(old$PrintreadablyP$002); } } Native.setSpecial(Stella.$CURRENTTRANSLATIONUNIT$, null); } } } } } }
7
public int execute() { boolean forceQuit = false; // Is there a --force param? if( this.getParamCount() != 0 ) { if( this.getParamAt(0).getString().equalsIgnoreCase("-f") || this.getParamAt(0).getString().equalsIgnoreCase("--force") ) forceQuit = true; else this.getFactory().getServer().getLogger().warning( "Unrecognized option: "+this.getParamAt(0).getString() ); } this.getFactory().getServer().performQuit( forceQuit ); return 0; }
3
public double increaseDamage(double damage){ double temp = damage - weaponItem.getAttackScore(); return temp; }
0
public void addDebito(String nomeCliente, double acrecimo)throws ExceptionGerentePessoa{ Cliente c = getCliente(nomeCliente); if(acrecimo >0){ c.addDebito(acrecimo); }else{ throw new ExceptionPessoa("Tentativa de adocionar d��bito com valor negativo"); } }
1
public void build() { Material block = Material.getMaterial(98); int x = this.x; int z = this.z; for (int y = this.y; y < height + this.y; y++) { x = this.x; z = this.z; for (int i = 0; i < width; i++) { // draw the north edge for (int j = 0; j < length; j++) { Location loc = new Location(Bukkit.getWorld("world"), x, y, z); if ((maze[j][i] & 1) == 0) { loc.getBlock().setType(block); x++; loc.setX(x); loc.getBlock().setType(block); } else { loc.getBlock().setType(block); x++; loc.setX(x); loc.getBlock().setType(Material.AIR); } x++; } Location loc = new Location(Bukkit.getWorld("world"), x, y, z); loc.getBlock().setType(block); x = this.x; z++; // draw the west edge for (int j = 0; j < length; j++) { Location loc2 = new Location(Bukkit.getWorld("world"), x, y, z); if ((maze[j][i] & 8) == 0) { loc2.getBlock().setType(block); x++; loc2.setX(x); loc2.getBlock().setType(Material.AIR); } else { loc2.getBlock().setType(Material.AIR); x++; loc2.setX(x); loc2.getBlock().setType(Material.AIR); } x++; } Location loc3 = new Location(Bukkit.getWorld("world"), x, y, z); loc3.getBlock().setType(block); x = this.x; z++; } // draw the bottom line for (int j = 0; j < length; j++) { Location loc2 = new Location(Bukkit.getWorld("world"), x, y, z); loc2.getBlock().setType(block); x++; loc2.setX(x); loc2.getBlock().setType(block); x++; } Location loc3 = new Location(Bukkit.getWorld("world"), x, y, z); loc3.getBlock().setType(block); x = this.x; } }
7
public static void openImageAction () { String userhome = System.getProperty("user.dir"); JFileChooser openFC = new JFileChooser(userhome); //let the user browse for an image openFC.setAccessory(new ImagePreview(openFC)); openFC.setAcceptAllFileFilterUsed(false); // not all files are accepted openFC.addChoosableFileFilter(new ImageFilter()); //use the image filter class int fileToOpen = openFC.showOpenDialog(jsp); //open the dialog box in a jscrollpane String openImagePath = null; //to save the path of the selected image if (fileToOpen == JFileChooser.APPROVE_OPTION) { File file = openFC.getSelectedFile(); openImagePath = file.getAbsolutePath(); } try { image = ImageIO.read(new File(openImagePath)); } catch (IOException e) { System.err.println(e.getMessage()); } f.setTitle("WiMAP - " + openImagePath); panelCanvas.setPreferredSize(new Dimension(image.getWidth(), image.getHeight())); //important for the scroll bars sp.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); sp.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED); panelCanvas.openImage(image); /*Resize frame according to image*/ if (image.getWidth() > f.getWidth()) f.setExtendedState( f.getExtendedState()|JFrame.MAXIMIZED_HORIZ ); else if (image.getWidth() > f.getWidth()) f.setExtendedState( f.getExtendedState()|JFrame.MAXIMIZED_VERT ); else { f.pack(); f.setLocationRelativeTo(null); } panelCanvas.initialize(); }
4
public void synchronizeEconomy(boolean accounts, boolean ecoplayers) { try { if (accounts) { for (int i = 1; i <= getGreatestId(Economy.accountTable, "id"); i++) synchronizeAccount(i); } if (ecoplayers) { for (int i = 1; i <= getGreatestId(Economy.ecoPlayerTable, "uuid"); i++) for (User user : EdgeCoreAPI.userAPI().getUsers().values()) synchronizeEconomyPlayer(user.getUUID()); } } catch(Exception e) { e.printStackTrace(); } }
6
public static UserStatusEnum getStatusByName(String name) { if (StringUtils.isEmpty(name)) { return null; } for (UserStatusEnum status : values()) { if (StringUtils.equals(status.name(), name)) { return status; } } return null; }
3
private static List<String> splitValuesOrEmpty(String[] strings, int index) { if(index<strings.length) { String[] values = VALUES.split(strings[index]); return Arrays.asList(values); } return Collections.emptyList(); }
1
public static void main(String[]args) { BigInteger n = BigInteger.valueOf(2); n = n.pow(1000); BigInteger sum = BigInteger.valueOf(0); while(n.compareTo(BigInteger.ONE) > -1) { sum = sum.add(n.mod(BigInteger.TEN)); n = n.subtract(n.mod(BigInteger.TEN)); n = n.divide(BigInteger.TEN); } System.out.println(sum); }
1
public void insert(Node node) { if(this.indent < node.indent) { if(this.children.size() > 0) { if(this.children.get(0).indent != node.indent) throw new RuntimeException("children indentations must match"); } this.children.add(node); node.parent = this; }else { if(this.parent == null) throw new RuntimeException("Root node too indented?"); this.parent.insert(node); } }
4
private JMeterHTablePool(Configuration config, int poolsize,byte[] tableName, final boolean autoFlush,final long writeBufferSize) { tablePool = new HTablePool(config, poolsize, new HTableFactory() { @Override public HTableInterface createHTableInterface(Configuration config, byte[] tableName) { try { HTable hTable = new HTable(config, tableName); hTable.setAutoFlush(autoFlush); hTable.setWriteBufferSize(writeBufferSize); return hTable; } catch (IOException e) { throw new RuntimeException(e); } } }); }
1
private static String getShortName(final String name) { int n = name.lastIndexOf('/'); int k = name.length(); if (name.charAt(k - 1) == ';') { k--; } return n == -1 ? name : name.substring(n + 1, k); }
2
@Override public int decidePlay(int turn, int drawn, boolean fromDiscard) { double[] playVotes = new double[6]; for (int i=0; i < cylons.size(); i++) { int vote = cylons.get(i).cardPositionForReal(game, rack, drawn); playVotes[vote] += weights.get(i); } double bestVote = 0; int pos = 0; for (int i=0; i < playVotes.length; i++) { if (playVotes[i] > bestVote) { bestVote = playVotes[i]; pos = i; } } return pos == game.rack_size ? -1 : pos; }
4
public static boolean enableNagles(SocketDescriptor sock, boolean enable) { try { sock.channel.socket().setTcpNoDelay(!enable); } catch(java.net.SocketException e) { vlog.error("Could not " + (enable ? "enable" : "disable") + " Nagle's algorithm: " + e.getMessage()); return false; } return true; }
2
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { String text = request.getParameter("textBox"); String target = request.getParameter("target"); String sub = request.getParameter("sub"); if(text != null & target != null & sub != null) { String textAfterCheck = text.replace(target, sub); request.setAttribute("TextAfterFilters", textAfterCheck); } chain.doFilter(request, response); }
1
public String adaptadorFomatoHora(String tiempoSolicitado) { String tiempoSolicitadoAdaptado; switch (tiempoSolicitado) { case "15 minutos": tiempoSolicitadoAdaptado = "00:15:00"; break; case "30 minutos": tiempoSolicitadoAdaptado = "00:30:00"; break; case "45 minutos": tiempoSolicitadoAdaptado = "00:45:00"; break; case "1 hora": tiempoSolicitadoAdaptado = "01:00:00"; break; case "2 horas": tiempoSolicitadoAdaptado = "02:00:00"; break; default: tiempoSolicitadoAdaptado = tiempoSolicitado; } return tiempoSolicitadoAdaptado; }
5
double splitInfoDiscrete(int i) { String[] attributeValues = data.getAttributeValues(i); String[] array2 = data.getAttributeRange(i); int p_values = array2.length; //store number of instances having belonging to a certain class int[] nk = new int[p_values]; for (int j = 0; j < array2.length; j++) { for (int k = 0; k < attributeValues.length; k++) { if (attributeValues[k].compareTo(array2[j]) == 0) { nk[j]++; } } } float info = 0; for (int x = 0; x < nk.length; x++) { float tempo = nk[x] / (float) data.num_instances; if (tempo != 0 && tempo != 1) { info += (-1 * tempo) * (Math.log(tempo) / Math.log(2.0)); } //System.out.println(info); } if (info == 0) { return .000001; } return info; }
7
@Override public void execute(MapleClient c, MessageCallback mc, String[] splitted) throws Exception { if (splitted[0].equals("npc")) { int npcId = Integer.parseInt(splitted[1]); MapleNPC npc = MapleLifeFactory.getNPC(npcId); if (npc != null && !npc.getName().equals("MISSINGNO")) { npc.setPosition(c.getPlayer().getPosition()); npc.setCy(c.getPlayer().getPosition().y); npc.setRx0(c.getPlayer().getPosition().x + 50); npc.setRx1(c.getPlayer().getPosition().x - 50); npc.setFh(c.getPlayer().getMap().getFootholds().findBelow(c.getPlayer().getPosition()).getId()); npc.setCustom(true); c.getPlayer().getMap().addMapObject(npc); c.getPlayer().getMap().broadcastMessage(MaplePacketCreator.spawnNPC(npc, false)); // c.getPlayer().getMap().broadcastMessage(MaplePacketCreator.spawnNPC(npc, true)); } else { mc.dropMessage("You have entered an invalid Npc-Id"); } } else if (splitted[0].equals("removenpcs")) { MapleCharacter player = c.getPlayer(); List<MapleMapObject> npcs = player.getMap().getMapObjectsInRange(c.getPlayer().getPosition(), Double.POSITIVE_INFINITY, Arrays.asList(MapleMapObjectType.NPC)); for (MapleMapObject npcmo : npcs) { MapleNPC npc = (MapleNPC) npcmo; if (npc.isCustom()) { player.getMap().removeMapObject(npc.getObjectId()); } } } else if (splitted[0].equals("mynpcpos")) { Point pos = c.getPlayer().getPosition(); mc.dropMessage("CY: " + pos.y +" | X : " + pos.x +" | RX0: " + (pos.x + 50) + " | RX1: " + (pos.x - 50) + " | FH: " + c.getPlayer().getMap().getFootholds().findBelow(pos).getId()); } }
7
public boolean hasCollided(int Xa, int Ya) { int xMin = 0; int xMax = 7; int yMin = 3; int yMax = 7; for (int x = xMin; x < xMax; x++) { if (isSolidTile(Xa, Ya, x, yMin)) { return true; } } for (int x = xMin; x < xMax; x++) { if (isSolidTile(Xa, Ya, x, yMax)) { return true; } } for (int y = yMin; y < yMax; y++) { if (isSolidTile(Xa, Ya, xMin, y)) { return true; } } for (int y = yMin; y < yMax; y++) { if (isSolidTile(Xa, Ya, xMax, y)) { return true; } } return false; }
8
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