method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
034f6f48-7079-4c5a-bf70-0b17744575ad
3
@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); }
fd052d42-09f8-4622-a7a4-352938821ca4
6
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(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); } }); }
d18590fd-173a-41f7-919c-68c668fbd081
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)); }
11b370b7-f2b0-4779-8174-89010ff8bece
7
@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; }
9fce1501-5a25-4c25-8a77-8c5dae3fc0a3
0
protected boolean step() { controller.step(); return true; }
428fe0a6-5c12-41a1-899c-97c1be76e14b
2
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; }
94334b3f-0b9b-47fb-b1a4-159cde79983d
1
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); }
7b40a7a8-e9fc-4c4a-8170-c45b36e0e762
5
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(); } }
d0e76a27-376b-4be6-8964-77ded7abb875
4
private boolean anyMovement() { if (backward || forward || right || left) { return true; } return false; }
3b55957a-e348-48d6-9f5e-5b0e021cc80e
8
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()); } } } }
0c94fcf7-c6e2-40e5-ad8a-8bcf6b9fdcf3
5
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; }
f7a131c5-42eb-42ac-9b21-ebf21b242ea4
0
RLOGDatatypeProperties() { this.uri = "http://persistence.uni-leipzig.org/nlp2rdf/ontologies/rlog#" + name(); }
94fd6f8c-f42e-4e6a-b4e5-1a47253409ac
6
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; } } }
86adc5f0-0ed9-4c49-9650-d377e977973a
7
@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"))); } } }
70ece218-c3ce-403f-8594-dffed99accd2
4
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"; } }
b841e4ed-0844-421d-ac12-fac106b59752
8
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; }
19ed1813-8e29-4615-a013-da2f2575e05a
9
@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) { } }
5f792bd7-3001-483a-ae27-153ce3dff12b
4
@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; }
0cc9eb51-e969-4269-a1a0-a7897187bd18
7
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(); } } } } } }
5850f68e-7a0b-4761-8227-b41a9ecade24
1
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); }
dcd936bb-81d1-4483-adb0-edeb57e9a3a7
6
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); } } } } } }
b37a5dcd-7b47-4c21-b5dc-035bbbf5037f
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(); } } }
ce847d54-c2f6-4827-8e62-ba1d87c224f8
5
@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; } }
5b72f290-eb26-4a1a-99cd-55ea1555f088
8
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; }
39e12a38-11c2-4796-83d7-7565ed2c549d
4
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()); } } }
c32cec77-63d8-4cec-80f5-9f7438fb2be5
9
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; }
545bf4de-ee48-45b0-8738-63221bceaa98
6
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); }
6ddfdc54-aabc-490f-9664-762f05efc33f
0
public CommandEditConfig(CreeperWarningMain plugin) { this.plugin = plugin; }
f06ef9bd-b842-498d-96ad-cc24170474fc
0
public Chance not() { return new Chance(1 - probability); }
a3202162-82dc-4662-83b3-ccb52d9a6e55
8
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; }
3a2a01ed-713a-475f-8b73-ceaa5c61225a
4
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); }
e72547fe-bc7d-487c-858c-afc9f6d2b914
8
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); } }
d6da7116-bbb5-4c3d-8b1d-3e7e465777c3
7
@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(); } }
384dc97c-0e68-4195-9656-d00fe2e63167
2
@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); } } }
5cf678f3-2330-4755-ace1-18d3c2b20beb
8
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; }
e1899b84-3ff0-4c2f-8a97-d92b86889199
7
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]); }
0886bc54-68b6-4aae-8bc2-e52282c38126
2
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(); } } }
6fc16565-dc61-4a9b-83a0-7f62be38ad66
5
@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; } }
9a7216c1-1105-4d34-9863-63de176a8901
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; }
c5a520f2-1507-4e53-958c-2206c4cb21c3
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; }
b285262b-de55-4672-821b-c232027888db
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()); }
cedb60a4-cc7c-4900-af7c-cf91cd6102a8
6
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(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); } }); }
c91a3f2a-3c72-4065-86b5-1f9657f8e148
2
@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); }
fd6fec34-a9fe-4f54-b74c-abb64f7bc277
5
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; } }
4d7a4f07-6d06-4cc4-88f0-8dcaa2fba885
7
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; }
0293793f-137e-43f1-be08-8ed919702801
8
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; }
609b38ee-c66a-494d-a2cf-01f11ea986d1
4
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!"); } }
88a6d21d-fd9b-41db-885e-bb2bca093280
0
public void setName(String name) { this.name = name; setDirty(); }
454ccedd-074d-45c3-ad44-9e324204cc4d
4
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; }
4b3da367-9cac-463e-a0db-630fce4672fe
5
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); } } }
9533db15-fb04-4b76-8c7d-3fe43ef43902
2
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); } }
8c513f94-0d32-4665-afcc-f518ac105cb2
6
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; }
ea12b138-22b9-4830-aa6e-f48d6d7dbab4
0
public static ServiceManager getServices() { return _services; }
1e19c848-bb3d-4100-862b-0e2dc2c0ec3a
6
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)); } } } }
a77b2e1b-e4df-416d-8606-6976a50b57b1
4
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"); }
088e2232-da00-48b3-93c9-9eb19c17845c
8
@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(); }
43f7da6c-ffbc-4136-b779-b662ec62c5a5
2
@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(); }
e7e39c5e-be3f-4e63-8085-6cd6c8bcca98
8
@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); } }
83b1b814-ac13-4de4-ad54-39b7a869f4e9
5
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; } }
fc98760c-019a-450d-b203-69475dc65752
3
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."); } } }
c1ffdf0d-b777-420d-baea-3c721d6e9cae
0
@Override public String getName() { return "user"; }
9a815fb0-ddb2-464e-9ba8-d8175d104ad4
9
@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(); } } }
a177c9e8-0f01-411a-b34b-2a150b357b67
7
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_; }
05df119d-ea78-4064-b6f8-f4c86e4dd6f9
5
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); } } }
46ffa68a-2e4d-4f10-a799-8b749375cac8
1
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); } }); }
4963eca2-8880-4c75-bee9-861d75cfe2ef
8
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; }
b415d171-519b-4f6b-b9d2-da8c5bbbd274
7
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"); } }
9dd37b5b-b847-4fb3-b6a6-e41bc6dce245
9
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; }
6ce35b6f-06a1-4af0-aeea-0d2d4d51d46b
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(); }
d5bd7287-94d7-4b12-aee9-c20ee2a7963a
0
public WorldTest() { }
c058f54d-3c33-4172-b297-93f1e67b40f7
4
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; } }
fdeb1989-2b78-407c-90d5-3fdd562889f7
6
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; }
b3098d50-a644-4e34-b45c-a4d858ca5d47
0
public Location getLocation() { return location; }
cf1695a7-cd94-4ed0-b027-e5e47be338d7
9
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; }
ff1b7b61-3fe4-47dd-846e-33c6222a8067
6
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(); } }
e463ff79-da39-4c9e-9169-f72cbff0c178
3
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"); } } }
3a946b5b-a5c7-41e8-bfb6-bfbb71309ddb
9
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); }
4a1afe15-1ca6-4a4a-b892-49115209a98b
8
@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); }
3aacd1f5-c8e1-4032-8b13-5d11f059519d
6
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; }
7942062c-e7f5-4fa3-a4a2-9410dc8d4f3d
7
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); } } } } } }
6c8462f9-8fac-4118-9125-cf7e36777ecf
3
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; }
03400072-8c13-415d-ae1f-6f172d4048ee
0
public double increaseDamage(double damage){ double temp = damage - weaponItem.getAttackScore(); return temp; }
153c44e7-bd81-4ec3-9a7c-5de4d823f94b
1
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"); } }
35c1cfa1-8b79-4546-863a-490b9a24a694
7
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; } }
f68d4a91-ac0e-40c4-a1f3-63d91501d599
4
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(); }
f84f434c-6431-49d7-b85a-c6bf8212f583
6
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(); } }
bbadbf56-41ed-433f-9a84-3e5f4f16ad5c
3
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; }
18a25a17-1c02-40fa-bf4c-6f2d8c9bc8ef
1
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(); }
52edfbfd-c1d5-408c-9e32-825a72baf103
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); }
bf1ceaeb-a019-47ef-90f1-1d6b5f3bcdf4
4
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); } }
cda82e28-6724-4efe-9002-1a9aca166a4a
1
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); } } }); }
4e8decdb-d7b0-454d-81e8-65f8fc209862
2
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); }
e643a04a-5c93-4bc5-b298-e7c0435fd4f0
4
@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; }
dcf66516-b271-4888-ac20-0a1b00a8b662
2
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; }
28d570fe-39ef-46d0-9c5a-c6cdefe45f02
1
@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); }
202ab8bb-98ba-4b6f-8b9c-bc8c88b91c0e
5
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; }
e9b0d94a-4e00-4dd3-8a46-6267e0d414d6
7
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; }
f8fd89ae-1d3d-412b-8749-7d05e63a5d5d
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()); } }
91811347-7408-4a83-b05d-896e73318e7b
8
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; }
0cb8fcf6-5319-40ce-85d1-cc97fb4228ef
7
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."); }