text
stringlengths
14
410k
label
int32
0
9
private Feature getRandomFeature(Rarity rarity) { double whichFeature = (Math.random() * 4); // System.out.println("which feature " + whichFeature); if (whichFeature >= 0 && whichFeature < 1) { return itemBuilder.getRandomItem(rarity); } // creatures are more likely if (whichFeature >= 1 && whichFeature <= 2) { return creatureBuilder.getRandomCreature(rarity); } if (whichFeature > 2 && whichFeature < 3) { return fixtureBuilder.getRandomFixture(rarity); } if (whichFeature >= 3 && whichFeature < 4) { return new SoulSubstance(); } if (whichFeature >= 3.5) { return new DroppedAction(actionBuilder); } System.err.println("something went wrong in the rng in getRandomFeature"); return null; }
9
public static HSSFCellStyle getStyle(HSSFWorkbook wb,HSSFCellStyle style, Style htmlStyle,String [][]attr) { for(int x=0;x<attr.length;x++) { if("id".equals(attr[x][0])&&(!"".equals(attr[x][1]))) { String[][] idstyle = htmlStyle.getStyleMap().get("#"+attr[x][1]); if(idstyle!=null) { setStyle (wb,idstyle,style); } } } return style; }
4
public JPanel makeSelector(){ JPanel selectorPane = new JPanel(new BorderLayout()); selectorPane.add(new JLabel("")); String[] names; switch(source){ case "editArtist": names = new String[IO.getInstance().getFestival().getArtists().size()]; for(int i = 0; i < names.length; i++){ names[i] = IO.getInstance().getFestival().getArtists().get(i).getName(); } break; case "editStage": names = new String[IO.getInstance().getFestival().getStages().size()]; for(int i = 0; i < names.length; i++){ names[i] = IO.getInstance().getFestival().getStages().get(i).getName(); } break; case "editPerformance": names = new String[IO.getInstance().getFestival().getPerformances().size()]; for(int i = 0; i < names.length; i++){ names[i] = IO.getInstance().getFestival().getPerformances().get(i).getName(); } break; default: names = new String[0]; } final JList<String> list = new JList<String>(names); list.setSelectedIndex(0); JPanel okPane = new JPanel(new FlowLayout()); JButton ok = new JButton("OK"); ok.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { switch(source){ case "editArtist": ArtistPanel aPanel = new ArtistPanel(); frame.setContentPane(aPanel.editArtistPane(frame, list.getSelectedValue())); frame.setSize(new Dimension(300,200)); break; case "editStage": StagePanel sPanel = new StagePanel(); frame.setContentPane(sPanel.editStagePane(frame, list.getSelectedValue())); frame.setSize(new Dimension(275, 150)); break; case "editPerformance": PerformancePanel pPanel = new PerformancePanel(); frame.setContentPane(pPanel.editPerformancePane(frame, list.getSelectedValue())); frame.setSize(new Dimension(400,307)); break; } } }); okPane.add(ok); selectorPane.add(okPane, BorderLayout.SOUTH); selectorPane.add(new JScrollPane(list), BorderLayout.CENTER); frame.setSize(new Dimension(200,250)); frame.setResizable(true); return selectorPane; }
9
public Object revealRandomProductions() { Iterator it = objectToProduction.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); Object key = entry.getKey(); if (alreadyDone.contains(key)) continue; Production[] p = (Production[]) objectToProduction.get(key); addProductions(Arrays.asList(p)); alreadyDone.add(entry.getKey()); return key; } return null; }
2
public void toggleKey(int keyCode, boolean isPressed) { if (keyCode == KeyEvent.VK_W || keyCode == KeyEvent.VK_UP) { up.toggle(isPressed); } if (keyCode == KeyEvent.VK_S || keyCode == KeyEvent.VK_DOWN) { down.toggle(isPressed); } if (keyCode == KeyEvent.VK_A || keyCode == KeyEvent.VK_LEFT) { left.toggle(isPressed); } if (keyCode == KeyEvent.VK_D || keyCode == KeyEvent.VK_RIGHT) { right.toggle(isPressed); } }
8
public ImageAlgebraicOperations(String s, final PunctualOperationsMenu menu) { super(s); this.menu = menu; this.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Panel panel = (((Window) menu.getTopLevelAncestor()).getPanel()); if (panel.getImage() == null) { return; } JFileChooser chooser = new JFileChooser(); Image panelImage = panel.getImage(); chooser.addChoosableFileFilter(panel.fileFilter); chooser.setAcceptAllFileFilterUsed(false); chooser.setFileFilter(panel.fileFilter); chooser.showOpenDialog(menu); File file = chooser.getSelectedFile(); if (file != null) { Image image = null; try { image = Loader.loadImage(file); } catch (Exception ex) { new MessageFrame("Couldn't load the image"); return; } if (image.getHeight() != panelImage.getHeight() || image.getWidth() != panelImage.getWidth()) { new MessageFrame("Images must be of the same size"); return; } try { panel.setImage(doOperation(panelImage, image)); panel.repaint(); } catch (IllegalArgumentException i) { new MessageFrame(i.getMessage()); } } } }); }
6
@Override public void run() { //System.err.println("going!"); try { client = new Socket(targetIP, port); //open connection InputStream reader = client.getInputStream(); byte[] headerBuff = new byte[4]; byte[] buff = null; boolean header = true; int dataLength = 0; while (client.isConnected()) { if (header && reader.available() >= 4) { //if header and at least 4 bytes available parse header (header is 4 bytes) header = false; reader.read(headerBuff); dataLength = headerToInt(headerBuff); //System.out.println("Found " + dataLength / 7 + " APs!"); } else if (!header && reader.available() >= dataLength) { //if !header and complete message is available, parse message buff = new byte[dataLength]; reader.read(buff); data.add(bytesToMACandRSSI(buff)); //Add the MacRssiPair[] to the shared queue header = true; } Thread.sleep(100); } System.out.println("Connection to server lost..."); } catch (SocketException e) { System.err.println("Could not reach the WLANScanner :("); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
8
private void applyPatch(SinglePatch patch, boolean dryRun) throws IOException, PatchException { lastPatchedLine = 1; List<String> target; patch.targetFile = computeTargetFile(patch); if (patch.targetFile.exists() && !patch.binary) { target = readFile(patch.targetFile); if (patchCreatesNewFileThatAlreadyExists(patch, target)) return; } else { target = new ArrayList<String>(); } if (patch.mode==Mode.DELETE) { target = new ArrayList<String>(); } else { if (!patch.binary) { for (Hunk hunk : patch.hunks) { applyHunk(target, hunk); } } } if (!dryRun) { backup(patch.targetFile); writeFile(patch, target); } }
7
@Override protected void done() { //when it have finish downloading try { errorCode=process.waitFor(); get(); } catch (InterruptedException e) { } catch (ExecutionException e) { } catch (CancellationException e){ errorCode=-1; } switch(errorCode){ case -1://cancel button //Helper.logFunction("d"); JOptionPane.showMessageDialog(_DownloadFrame, "Download has been cancelled. Note partially downloaded to: \n" +Constants.CURRENT_DIR+urlEnd); break; case 0://nothing wrong so write to log //Helper.logFunction("d"); JOptionPane.showMessageDialog(_DownloadFrame, "Download has finished. Note downloaded to: \n" +Constants.CURRENT_DIR+urlEnd); break; case 3://error message of File IO JOptionPane.showMessageDialog(_DownloadFrame, "File IO error. Make sure the directory is safe to write to. Or not denied by your anti-virus."); break; case 4://error message of Network JOptionPane.showMessageDialog(_DownloadFrame, "Network error. Make sure you are connected to the internet correctly. Or link is invalid"); break; case 8://error message of Sever issue JOptionPane.showMessageDialog(_DownloadFrame, "Server issued error. Server could be down. Please try again later."); break; default://error message of generic JOptionPane.showMessageDialog(_DownloadFrame, "An error has occured. Please try again. The error code is: "+errorCode); break; } this._DownloadFrame.dispose(); if (errorCode==0){ VideoOperations.loadAndPreview(Constants.CURRENT_DIR+urlEnd, "00:00:00", "00:00:30"); } }
9
@Override public void paintComponent(Graphics g){ super.paintComponent(g); setBackground(Color.black); if (bflag == 1) { for (int i = 0; i < bullet.size(); i++) { bullet.get(i).draw(g); } } square.draw(g); ufo.draw(g); for (int i = 0; i < shipr0.size(); i++) { shipr0.get(i).draw(g); } for (int i = 0; i < shipr1.size(); i++) { shipr1.get(i).draw(g); } for (int i = 0; i < shipr2.size(); i++) { shipr2.get(i).draw(g); } for (int i = 0; i < shipr3.size(); i++) { shipr3.get(i).draw(g); } for (int i = 0; i < shipr4.size(); i++) { shipr4.get(i).draw(g); } if (uflag == 1) { for (int i = 0; i < ubullet.size(); i++) { ubullet.get(i).draw(g); } } }
9
public static ArrayList<Tuple> correct(String input) throws FileNotFoundException { // System.out.println("TestData -- " + input); StringTokenizer tokenizer = new StringTokenizer(input, " !?.;,"); String misSpelt = ""; String misSpeltPPOS = ""; ArrayList<String> contextWord = new ArrayList<String>(); ArrayList<String> coOccurenceWord = new ArrayList<String>(); ArrayList<String> contextPOS = new ArrayList<String>(); boolean beforeOccurence = true; // Assume a sentence has just one // spelling error // TODO: For more than one a repeated guess and correct learn method // will be followed while (tokenizer.hasMoreElements()) { String token = tokenizer.nextToken(); ArrayList<String> possibility_list = Dictionary.dictionary .get(token.length()); boolean found = false; for (String str : possibility_list) { str = str.replaceAll("[^a-zA-Z]", ""); token = token.replaceAll("[^a-zA-Z]", ""); token = token.toLowerCase(); int edit_dist = LD.getLD(str, token, matrix); if (edit_dist == 0) { found = true; break; } } if (!found) { misSpelt = token; beforeOccurence = false; } else { if (beforeOccurence) contextWord.add(token); String POS; if (PartsOfSpeech.wordPOSMap.containsKey(token)) POS = PartsOfSpeech.wordPOSMap.get(token); else { PartsOfSpeech.wordPOSMap.put(token, "UND"); // code for POS = "UND"; } if (beforeOccurence) contextPOS.add(POS); coOccurenceWord.add(token); } } // Once the list of word to be corrected, context words, collocation // words, context POS and // collocation POS is found, we need to find the candidates and then // find the respective probabilities // Getting candidates baseed on Edit distance // System.out.println("Misspelt " + misSpelt); ArrayList<String> candidates = getCandidates(misSpelt); ArrayList<Tuple> correction = new ArrayList<Tuple>(); for (String cand : candidates) { misSpeltPPOS = PartsOfSpeech.wordPOSMap.get(cand); long rank = 0; if (misSpeltPPOS != null) rank = getIntersection(cand, misSpeltPPOS, contextWord, contextPOS, coOccurenceWord); Tuple t = new Tuple(); t.word = cand; t.rank = rank; // if (rank != 0) correction.add(t); } return correction; }
9
private void copyRGBtoABGR(ByteBuffer buffer, byte[] curLine) { if(transPixel != null) { byte tr = transPixel[1]; byte tg = transPixel[3]; byte tb = transPixel[5]; for(int i=1,n=curLine.length ; i<n ; i+=3) { byte r = curLine[i]; byte g = curLine[i+1]; byte b = curLine[i+2]; byte a = (byte)0xFF; if(r==tr && g==tg && b==tb) { a = 0; } buffer.put(a).put(b).put(g).put(r); } } else { for(int i=1,n=curLine.length ; i<n ; i+=3) { buffer.put((byte)0xFF).put(curLine[i+2]).put(curLine[i+1]).put(curLine[i]); } } }
6
public String stSendOrCancelEmail1(int dataId,int ExpVal,String flow ) { int actVal=1000; String returnVal=null; hm.clear(); hm=STFunctionLibrary.stMakeData(dataId, "Email"); String action = hm.get("Action"); String widgetType=hm.get("WidgetType"); STCommonLibrary comLib=new STCommonLibrary(); Vector<String> xPath=new Vector<String>(); Vector<String> errorMsg=new Vector<String>(); String successmsg = ""; String errormsg = ""; try { if(widgetType.equalsIgnoreCase("OAuth")) { xPath.add(OAUTH_WIDGET_SHARE_BUTTON); errorMsg.add("Share Button is not present on WIdget"); }else { xPath.add(EMAIL_CANCEL_BUTTON); errorMsg.add("Cancel button is not present"); xPath.add(EMAIL_SEND_BUTTON); errorMsg.add("Send Button is not present"); } comLib.stVerifyObjects(xPath, errorMsg, "STOP"); xPath.clear(); errorMsg.clear(); Block: { /* Executing Tests if widget type is OAuth */ if(widgetType.equalsIgnoreCase("OAuth")) { comLib.stClick(OAUTH_WIDGET_SHARE_BUTTON, "Send Button is not present", "STOP"); /* Wait for processing */ try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } } /* If no error messages appear on WIdget and email share is successful */ if(browser.isElementPresent(OAUTH_WIDGET_DONE_SCREEN)) { /* Grabbing message on Done screen */ String successMsg=browser.getText(OAUTH_WIDGET_DONE_SCREEN_MESSAGE); if(successMsg.equalsIgnoreCase("Your message was successfully shared!")) { actVal= 0; /*Email send successfully.*/ System.out.println(successMsg); break Block; } } else { if(browser.isElementPresent(OAUTH_WIDGET_CAPTCHA_SCREEN)) { actVal= 3; /*Failed to Send or Cancel email.*/ break Block; } else /* log for failure */ { actVal= 2; /*Failed to Send or Cancel email.*/ break Block; } } } } catch (SeleniumException sexp) { Reporter.log(sexp.getMessage()); } returnVal=STFunctionLibrary.stRetValDes(ExpVal, actVal, "stSendOrCancelEmail1",flow, hm); if(flow.contains("STOP")){ assertEquals("PASS",returnVal); } return returnVal; }
8
@Override public void actionPerformed(ActionEvent a) { if(a.getSource() == TypeSel){ Clear(); switch(TypeSel.getSelectedIndex()){ case posCartLine: initCartesianLine(); break; case posVecLine: initVectorLine(); break; case posCartPlane: initCartesian(); break; case posVecPlane: initVector(); break; default: break; } } this.update(true); }
5
public Timestamp getBooktimeByOrdernumber(Statement statement,String ordernumber)//根据订单号获取下单时间 { Timestamp result = null; sql = "select booktime from ParkRelation where ordernumber = '" + ordernumber +"'"; try { ResultSet rs = statement.executeQuery(sql); while (rs.next()) { result = rs.getTimestamp("booktime"); } } catch (SQLException e) { System.out.println("Error! (from src/Fetch/ParkRelation.getBooktimeByOrdernumber())"); // TODO Auto-generated catch block e.printStackTrace(); } return result; }
2
public void Init(boolean solid) { if (!solid) { _streamPos = 0; _pos = 0; } }
1
public boolean equals(PixImage image) { int width = getWidth(); int height = getHeight(); if (image == null || width != image.getWidth() || height != image.getHeight()) { return false; } for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { if (! (getRed(x, y) == image.getRed(x, y) && getGreen(x, y) == image.getGreen(x, y) && getBlue(x, y) == image.getBlue(x, y))) { return false; } } } return true; }
8
private void sendCmdOutToAll(String data) throws TimeoutException { PooledBlockingClient pbc[] = blockingClientPool.getOneBlockingClientForAllActiveHosts(); if (pbc == null) { throw new TimeoutException("we do not have any client array [pbc] to connect to server!"); } for (int i = 0; i < pbc.length; i++) { try { BlockingClient bc = pbc[i].getBlockingClient(); if (bc == null) { throw new TimeoutException("we do not have any client[bc] to connect to server!"); } bc.sendBytes(data, charset); } catch (IOException e) { if (pbc != null) { logger.log(Level.WARNING, "We had an ioerror will close client! " + e, e); pbc[i].close(); } } finally { blockingClientPool.returnBlockingClient(pbc[i]); pbc[i] = null; } } }
5
private Position getTertiaryPowerFailurePosition() { // Calculate T1 Position final int directionInt = parentPowerFailure.getDirectionInt(); final Direction direction = Direction.values()[directionInt]; final Position squareOne = direction.newPosition(parentPowerFailure.pos); // Calculate T2 Position final int dirIntTwo = (directionInt - 1 < 0) ? Direction.values().length - 1 : directionInt - 1; final Position squareTwo = (Direction.values()[dirIntTwo]).newPosition(parentPowerFailure.pos); // Calculate T3 Position final int dirIntThree = (directionInt + 1 > Direction.values().length - 1) ? 0 : directionInt + 1; final Position squareThree = (Direction.values()[dirIntThree]).newPosition(parentPowerFailure.pos); // Put T1, T2 and T3 in Position List List<Position> common = new ArrayList<Position>(); common.add(squareOne); common.add(squareTwo); common.add(squareThree); // Get Random Position of T1, T2 and T3 final Random random = new Random(); final int randomIndex = random.nextInt(common.size()); // Return the Random Position return common.get(randomIndex); }
2
public void using(int usingTimeMillis) throws ParkingException { try { TimeUnit.MILLISECONDS.sleep(usingTimeMillis); } catch (InterruptedException e) { throw new ParkingException(e); } }
1
@SuppressWarnings("static-access") void setupOutgoingCommand(OutgoingCommand command) throws EnetException { Channel channel = this.channels.get(command.command.channelID()); this.outgoingDataTotal += command.command.length() + (command.fragmentLength & 0xFFFF); if (command.command.channelID() == 0xFF) { this.outgoingReliableSequenceNumber++; command.reliableSequenceNumber = this.outgoingReliableSequenceNumber; command.unreliableSequenceNumber = 0; } else if (command.command.flags().contains(Protocol.CommandFlag.Acknowledge)) { channel.outgoingReliableSequenceNumber++; channel.outgoingUnreliableSequenceNumber = 0; command.reliableSequenceNumber = channel.outgoingReliableSequenceNumber; command.unreliableSequenceNumber = 0; } else if (command.command.flags().contains(Protocol.CommandFlag.Unsequenced)) { this.outgoingUnsequencedGroup++; command.reliableSequenceNumber = 0; command.unreliableSequenceNumber = 0; } else { if (command.fragmentOffset == 0) channel.outgoingUnreliableSequenceNumber++; command.reliableSequenceNumber = channel.outgoingReliableSequenceNumber; command.unreliableSequenceNumber = channel.outgoingUnreliableSequenceNumber; } command.sendAttempts = 0; command.sentTime = 0; command.roundTripTimeout = 0; command.roundTripTimeoutLimit = 0; command.command.setReliableSequenceNumber(command.reliableSequenceNumber); switch (command.command.command()) { case SendUnreliable: ((Protocol.SendUnreliable) command.command).setUnreliableSequenceNumber(command.unreliableSequenceNumber); break; case SendUnsequenced: ((Protocol.SendUnsequenced) command.command).setUnsequencedGroup(this.outgoingUnsequencedGroup); break; } if (command.command.flags().contains(Protocol.CommandFlag.Acknowledge)) this.outgoingReliableCommands.add(command); else this.outgoingUnreliableCommands.add(command); }
7
* @return the meeting with the requested ID, or null if it there is none. */ public Meeting getMeeting(int id) { if(id >= meetingList.size()) { return null; } return meetingList.get(id); }
1
public Missiletab(ConsoleApp theApplication, String launcherId, List<WarUIEventsListener> allListeners) { this.theApplication = theApplication; this.allListener = allListeners; this.launcherID=launcherId; missileID = new TextField(); destination = new TextField(); damage = new TextField(); flytime = new TextField(); Button add = new Button("Resquest & Add missile from server"); Button connect = new Button("Connect to server"); this.setMaxSize(285.0, 371.0); missileID.setPromptText("missileID"); missileID.setMaxSize(221, 25); missileID.setLayoutX(14.0); missileID.setLayoutY(37.0); destination.setPromptText("destination"); destination.setMaxSize(221, 25); destination.setLayoutX(14.0); destination.setLayoutY(69.0); damage.setPromptText("damage"); damage.setMaxSize(221, 25); damage.setLayoutX(14.0); damage.setLayoutY(101.0); flytime.setPromptText("flytime"); flytime.setMaxSize(221, 25); flytime.setLayoutX(14.0); flytime.setLayoutY(133.0); add.setLayoutX(14.0); add.setLayoutY(167.0); connect.setLayoutX(14.0); connect.setLayoutY(5.0); add.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { new Thread (new Runnable() { @Override public void run() { String id = missileID.getText(); String dest = destination.getText(); String damageT = damage.getText(); String flyTime = flytime.getText(); if (id.isEmpty() || dest.isEmpty() || damageT.isEmpty()) { } for (WarUIEventsListener l : allListener) { // sending missile details to the relevant GUI launcher l.addMissileThroughClient(id, dest, damageT, flyTime, launcherID); } } }).start(); } }); connect.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { new Thread(new Runnable() { @Override public void run() { for (WarUIEventsListener l : allListener) { // sending missile details to the relevant GUI launcher l.connectToServer(); } } }).start(); } }); getChildren().addAll(connect, missileID, destination, damage, flytime,add); }
5
public void save()throws IOException{ props.store(new FileOutputStream(file), des); }
0
public static void main(String[] args) { SortVector sv = new SortVector(new StringCompare()); // Open the file which contains the words you want to add try { FileInputStream fstream = new FileInputStream("newoutput1.txt"); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); FileOutputStream sortedWordBook = new FileOutputStream( "SortedWordbook.txt"); String newWord, currentWord; while ((newWord = br.readLine()) != null) { newWord = newWord.trim(); sv.addElement(newWord); } sv.sort(); Enumeration e = sv.elements(); int wordCount = 0; while (e.hasMoreElements()) { currentWord = newWord; newWord = ((String) e.nextElement()).toLowerCase(); if (currentWord != null && currentWord.equals(newWord)) { continue; } System.out.println(newWord); sortedWordBook.write(newWord.getBytes()); sortedWordBook.write("\r\n".getBytes()); wordCount++; } String totalWords = "Total Words: " + wordCount; sortedWordBook.write(totalWords.getBytes()); sortedWordBook.write("\r\n".getBytes()); fstream.close(); sortedWordBook.close(); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } }
6
private static void printUsage() { System.out.println("FlowDroid (c) Secure Software Engineering Group @ EC SPRIDE"); System.out.println(); System.out.println("Incorrect arguments: [0] = apk-file, [1] = android-jar-directory"); System.out.println("Optional further parameters:"); System.out.println("\t--TIMEOUT n Time out after n seconds"); System.out.println("\t--SYSTIMEOUT n Hard time out (kill process) after n seconds, Unix only"); System.out.println("\t--SINGLEFLOW Stop after finding first leak"); System.out.println("\t--IMPLICIT Enable implicit flows"); System.out.println("\t--NOSTATIC Disable static field tracking"); System.out.println("\t--NOEXCEPTIONS Disable exception tracking"); System.out.println("\t--APLENGTH n Set access path length to n"); System.out.println("\t--CGALGO x Use callgraph algorithm x"); System.out.println("\t--NOCALLBACKS Disable callback analysis"); System.out.println("\t--LAYOUTMODE x Set UI control analysis mode to x"); System.out.println("\t--ALIASFLOWINS Use a flow insensitive alias search"); System.out.println("\t--NOPATHS Do not compute result paths"); System.out.println("\t--AGGRESSIVETW Use taint wrapper in aggressive mode"); System.out.println(); System.out.println("Supported callgraph algorithms: AUTO, RTA, VTA"); System.out.println("Supported layout mode algorithms: NONE, PWD, ALL"); }
0
public void notify(int ack, String fileName) { switch (ack) { case Global.READACK: masterLogger.logMessage("===> done reading " + fileName); break; case Global.WRITEACK: masterLogger.logMessage("===> done writing " + fileName + "in primary replica"); break; case Global.BROADCASTSTARTACK: masterLogger.logMessage("===> Start flushing " + fileName + " to all replicas"); break; case Global.BROADCASTENDACK: masterLogger.logMessage("===> done flushing " + fileName + " to all replicas"); break; default: masterLogger.logMessage("===> Aport "); break; } }
4
private void readConstantPool(final DataInputStream in) throws IOException { final int count = in.readUnsignedShort(); constants = new ArrayList(count); // The first constant is reserved for internal use by the JVM. constants.add(0, null); // Read the constants. for (int i = 1; i < count; i++) { constants.add(i, readConstant(in)); switch (((Constant) constants.get(i)).tag()) { case Constant.LONG: case Constant.DOUBLE: // Longs and doubles take up 2 constant pool entries. constants.add(++i, null); break; } } }
3
public static void main(String[] args) { try { String name = "MASTER"; if (args.length >= 1) { name = args[0]; } new MessagingNode(name); } catch (Exception e) { log.fatal("Toal failure to open a socket connection.", e); } }
2
public void selectionChanged() { NSRelation or; int i, oc; SObjectTableModel tm; oc = 0; for (i = 0; i < this.M.getSize(); i++) { if (this.M.getObjectAt(i).isSelected()) { oc++; this.o = (NSObject) this.M.getObjectAt(i); } } if (oc == 1) { this.nameField.setText(this.o.getName()); if (this.o.getSnippet().isRelation()) { or = (NSRelation) this.o; this.description.setText(Messages.tr("relates") + " (" + or.getFrom().getName() + ", " + or.getTo().getName() + ")"); } else { this.description.setText(Messages.tr("entity_class") + ": " + this.o.getSnippet().getName() + " : " + this.o.getSnippet().getBase()); } // Prepare array list this.arrayIndex.removeAllItems(); this.arrayIndex.addItem(new NSArray(Messages.tr("no_index"), 0)); for (i = 0; i < this.M.getArrayCount(); i++) { this.arrayIndex.addItem(this.M.getArray(i)); } if (this.o.getArrayIndex() >= 0) { this.arrayIndex.setSelectedIndex(this.o.getArrayIndex() + 1); } } if (oc > 1) { this.nameField.setText(""); this.description.setText(Messages.tr("multiple_selection")); this.arrayIndex.setSelectedIndex(-1); this.o = null; } if (oc == 0) { this.nameField.setText(""); this.description.setText(Messages.tr("no_selection")); this.arrayIndex.setSelectedIndex(-1); this.o = null; } tm = new SObjectTableModel(this.o); this.attrTable.setModel(tm); if (oc == 1) { this.attrTable.getColumnModel().getColumn(1).setCellEditor(new SObjectCellEditor(this.o)); } }
9
@Override protected void parseInternal(Method method, Map<String, Integer> paramIndexes, Map<String, Integer> batchParamIndexes) throws DaoGenerateException { super.parseInternal(method, paramIndexes, batchParamIndexes); MongoUpdate updateShell = method.getAnnotation(MongoUpdate.class); upsert = updateShell.upsert(); multi = updateShell.multi(); Class<?>[] paramTypes = method.getParameterTypes(); parseModifierShell(updateShell.modifier(), paramTypes, paramIndexes); }
1
public int searchNumber(int search,String option) { int start = 0; int position = -1; int end = array.length - 1; while (start <= end) { int mid = (start + end) / 2; if (search == array[mid]) { position = mid; if(option.equalsIgnoreCase("first")){ end = mid-1; } else if(option.equalsIgnoreCase("last")){ start = mid+1; }else return position; } if (search < array[mid]) { end = mid - 1; } else { start = mid + 1; } } return position; }
5
private String isHyperlink(Point p) { if (getDocument() instanceof HTMLDocument) { int pos = viewToModel(p); if (pos >= 0) { try { HTMLDocument doc = (HTMLDocument) getDocument(); if (doc != null) { Element elem = doc.getCharacterElement(pos); if (elem != null) { AttributeSet a = elem.getAttributes(); // FIXME!!!: If an image is hyperlinked, the href attribute will be truncated at the // position where the first whitespace appears, if the code base is remote. // Enumeration e = a.getAttributeNames(); // while(e.hasMoreElements()){ // Object o =e.nextElement(); // System.out.println(o+"="+a.getAttribute(o)); // } if (a != null) { AttributeSet b = (AttributeSet) a.getAttribute(HTML.Tag.A); if (b != null) { String s = (String) b.getAttribute(HTML.Attribute.HREF); if (s == null) return s; return FileUtilities.httpDecode(s); } } } } } catch (Exception e) { e.printStackTrace(); return null; } } } return null; }
8
private HashMap<AbstractComponent, Integer> getWordMap( AbstractComponent component, HashMap<AbstractComponent, Integer> map) throws BookException { if (component.getType() == EComponentType.WORD) { Integer count = map.get(component); map.put(component, count == null ? 1 : ++count); } else if (component.getType() == EComponentType.CHARACTER) { } else { try { Iterator<AbstractComponent> iterator = component.getIterator(); while (iterator.hasNext()) { map.putAll(getWordMap(iterator.next(), map)); } } catch (ComponentException e) { throw new BookException(e); } } return map; }
5
private void drawAlign(int x, int y, int w, int _h, Graphics2D g, String _type) { int N = _h / 2; int i; int stepH = (_h / N); int indent = (int) (w * 0.1); int rw = w - indent; if (stepH <= 1) { stepH = 1; } int h = y + (stepH / 2 + 1); int type; if (_type.equals("left")) { type = 0; } else if (_type.equals("right")) { type = 1; } else if (_type.equals("center")) { type = 2; } else { type = 3; } g.setColor(Color.DARK_GRAY); for (i = 0; i < N; i++) { double rnd = 0.3 * Math.random(); switch (type) { case 0: { int RW = (int) (rw - (rw * rnd)); g.drawLine(x + indent, h, x + RW, h); break; } case 1: { int M = (int) (rw * rnd); g.drawLine(x + indent + M, h, x + rw, h); break; } case 2: { int M = (int) (rw * rnd); int RW = (int) (rw - M); g.drawLine(x + indent + M, h, x + RW, h); break; } case 3: { g.drawLine(x + indent, h, x + rw, h); break; } } h += stepH; } }
9
@Override protected void fireActionPerformed(ActionEvent event) { Container w = getWindow(); if (isSelected()) { adjustWindow(w); w.setVisible(true); w.requestFocus(); } else { w.setVisible(false); } }
1
public final LogoParser.assignment_return assignment() throws RecognitionException { LogoParser.assignment_return retval = new LogoParser.assignment_return(); retval.start = input.LT(1); Object root_0 = null; Token MAKE30=null; Token ID31=null; LogoParser.expression_return expression32 =null; Object MAKE30_tree=null; Object ID31_tree=null; try { // /home/carlos/Proyectos/logojava/Logo.g:83:2: ( MAKE ID expression ) // /home/carlos/Proyectos/logojava/Logo.g:83:4: MAKE ID expression { root_0 = (Object)adaptor.nil(); MAKE30=(Token)match(input,MAKE,FOLLOW_MAKE_in_assignment398); MAKE30_tree = (Object)adaptor.create(MAKE30) ; adaptor.addChild(root_0, MAKE30_tree); ID31=(Token)match(input,ID,FOLLOW_ID_in_assignment400); ID31_tree = (Object)adaptor.create(ID31) ; adaptor.addChild(root_0, ID31_tree); pushFollow(FOLLOW_expression_in_assignment402); expression32=expression(); state._fsp--; adaptor.addChild(root_0, expression32.getTree()); retval.value = new Assignment((ID31!=null?ID31.getText():null),(expression32!=null?expression32.value:null)); } retval.stop = input.LT(-1); retval.tree = (Object)adaptor.rulePostProcessing(root_0); adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); } catch (RecognitionException re) { reportError(re); recover(input,re); retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re); } finally { // do for sure before leaving } return retval; }
3
public void setPaused(boolean paused) { if(paused) { if(!this.paused) { for(final String key : currentClips.keySet()) { currentClips.get(key).stop(); } this.paused = true; } } else { if(this.paused) { for(final String key : currentClips.keySet()) { currentClips.get(key).start(); } this.paused = false; } } }
5
@Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { stack.push(qName); for(int i = 0; i < attributes.getLength(); i ++) { String attrname = attributes.getQName(i); String attrvalue = attributes.getValue(i); System.out.println("========================"); System.out.println(attrname + "=" + attrvalue); } }
1
@Override public boolean equals(Object object) { if (object instanceof Contact){ Contact contact = (Contact) object; return contact.id == id; } return false; }
1
public static List<Currency> formatOutputs(JSONArray results) { final List<Currency> ret = new ArrayList<Currency>(); for (int i = 0; i < results.length(); i++) { JSONObject r = null; if (results.get(i) instanceof JSONObject) r = (JSONObject) results.get(i); if (r != null) { final Currency c = new Currency(); if (r.has("name")) c.setName(r.get("name").toString()); c.setNumber(r.get("number").toString()); c.setSymbol(r.get("symbol").toString()); c.setUuid(r.get("uuid").toString()); ret.add(c); } } return ret; }
4
private void checkForPath(){ CollisionResults [] results = new CollisionResults [4]; for(int i = 0; i < results.length; i++){ results[i] = new CollisionResults(); } getStageNode().getChild("TerrainNode").collideWith(new Ray(Vector3f.ZERO, Vector3f.UNIT_X), results[0]); // CollisionResults results2 = new CollisionResults(); getStageNode().getChild("TerrainNode").collideWith(new Ray(Vector3f.ZERO, Vector3f.UNIT_X.negate()), results[1]); // CollisionResults results3 = new CollisionResults(); getStageNode().getChild("TerrainNode").collideWith(new Ray(Vector3f.ZERO, Vector3f.UNIT_Z), results[2]); // CollisionResults results4 = new CollisionResults(); getStageNode().getChild("TerrainNode").collideWith(new Ray(Vector3f.ZERO, Vector3f.UNIT_Z.negate()), results[3]); if(results[0].size() <= 0){ newPoint = new Vector3f(0, FastMath.HALF_PI, 0); // newPoint = Vector3f.UNIT_X; }else if(results[1].size() <= 0){ newPoint = new Vector3f(0, -FastMath.HALF_PI, 0); // newPoint = Vector3f.UNIT_X.negate(); }else if(results[2].size() <= 0){ newPoint = Vector3f.UNIT_Z; }else if(results[3].size() <= 0){ newPoint = Vector3f.UNIT_Z.negate(); }else{ float dist = spatial.getWorldTranslation().distance(results[0].getClosestCollision().getContactPoint()); int index = 0; for(int i = 1; i < results.length; i++){ if(spatial.getWorldTranslation().distance(results[i].getClosestCollision().getContactPoint()) > dist){ dist = spatial.getWorldTranslation().distance(results[i].getClosestCollision().getContactPoint()); index = i; } } newPoint = results[index].getClosestCollision().getContactPoint(); // if(spatial.getWorldTranslation().distance(results1.getClosestCollision().getContactPoint()) > // spatial.getWorldTranslation().distance(results2.getClosestCollision().getContactPoint())){ // newPoint = Vector3f.UNIT_X; // }else{ // newPoint = Vector3f.UNIT_X.negate(); // } } current_TimerObMove = timer_ObstacleMove; }
7
static void addTab(final JTabbedPane tabPane) { if (!SwingUtilities.isEventDispatchThread()) { try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { addTab(tabPane); } }); } catch (InvocationTargetException | InterruptedException e1) { } return; } final Shell jsh = new Shell(); tabPane.addTab("Jsh", jsh); jsh.setSize(tabPane.getSize()); final int index = tabPane.indexOfComponent(jsh); JPanel tabPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0)); tabPanel.setOpaque(false); JLabel label = new JLabel() { private static final long serialVersionUID = 1L; @Override public String getText() { int i = tabPane.indexOfComponent(jsh); if (i != -1) { return tabPane.getTitleAt(i); } return null; } }; tabPanel.add(label); label.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5)); JButton button = new JButton() { private static final long serialVersionUID = 1L; { int size = 17; setPreferredSize(new Dimension(size, size)); setToolTipText("Close this tab"); // Make the button look the same for all Laf's setUI(new BasicButtonUI()); setContentAreaFilled(false); setFocusable(false); setBorder(BorderFactory.createEtchedBorder()); setBorderPainted(false); addMouseListener(mouseListener); setRolloverEnabled(true); } @Override public void updateUI() { } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g.create(); if (getModel().isPressed()) { g2.translate(1, 1); } g2.setStroke(new BasicStroke(2)); g2.setColor(Color.BLACK); if (getModel().isRollover()) { g2.setColor(Color.MAGENTA); } int delta = 6; g2.drawLine(delta, delta, getWidth() - delta - 1, getHeight() - delta - 1); g2.drawLine(getWidth() - delta - 1, delta, delta, getHeight() - delta - 1); g2.dispose(); } }; tabPanel.add(button); tabPanel.setBorder(BorderFactory.createEmptyBorder(2, 0, 0, 0)); tabPane.setTabComponentAt(index, tabPanel); String closeTab = "closeTab"; jsh.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_W, InputEvent.CTRL_MASK | InputEvent.SHIFT_MASK), closeTab); AbstractAction closeAction = new AbstractAction() { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { tabPane.remove(jsh); if (tabPane.getTabCount() == 0) { Container topLevel = tabPane.getTopLevelAncestor(); topLevel.setVisible(false); if (topLevel instanceof Window) { ((Window) topLevel).dispose(); } else { // something strange happened, just exit System.exit(0); } } } }; jsh.getActionMap().put(closeTab, closeAction); button.addActionListener(closeAction); tabPane.setSelectedIndex(index); }
7
@Override public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { String myCmd = cmd.getName().toLowerCase(); Commands c = new Commands((Player) sender); boolean ret = true; if (myCmd.equals("pmhelp")) { c.Help(); } else if (myCmd.equals("pmread")) { int n = 0; if (args.length > 0) { try { n = Integer.parseInt(args[0]); } catch (Exception ex) { c.Close(); return false; } ret = c.Read(n); } else { ret = c.Read(n); } } else if (myCmd.equals("pmsend")) { if (args.length >= 3) { List<String> msg_text = new ArrayList<String>(Arrays.asList(args)); ret = c.Send(args[0], args[1], msg_text.subList(2, msg_text.size())); } } else if (myCmd.equals("pmlist")) { ret = c.List(); } c.Close(); return ret; }
7
@Override public Sentence_tree bfs_function(String function){ LinkedList<Sentence_tree> queue = new LinkedList<Sentence_tree>(); queue.add(this); while(!queue.isEmpty()){ Sentence_tree current = queue.pop(); if(current.root.function.equals(function)){ return current; } for(int index = 0; index < current.children.length; index++){ queue.addLast(current.children[index]); } } return null; }
3
public static Thread transformMissionTriggerThread(final String currentLang, final String outputPath, final String fileName, final String[][] commonContent) { Thread currentThread = new Thread(new Runnable() { @Override public void run() { StringBuilder allContent = new StringBuilder(); allContent.append(" return array (\r\n"); int index = 0; NoticeMessageJFrame.setTotalFileCountMap(currentLang + ":" + fileName, commonContent.length - 1); for (int i = 1; i < commonContent.length; i++) { // NoticeMessageJFrame.setCurrentProcessing(1); Map<String, String> singleRowInfo = BuildConfigContent.buildMissionTriggerSingleRowStr(commonContent[i], index); String id = singleRowInfo.get("id"); if (!id.isEmpty()) {//空id 直接无视 index++; String singleItemInfo = singleRowInfo.get("singleRowInfo"); String currentAllItemInfo = singleRowInfo.get("allRowsInfo"); String descFile = BuildConfigLogic.buildSingleRowStoredPath(currentLang, id, outputPath, fileName, fileName); try { FileUtils.writeToFile("<?php\r\n return " + singleItemInfo, descFile, "UTF-8"); } catch (FileNotFoundException ex) { NoticeMessageJFrame.showMessageDialogMessage(ex); } catch (IOException ex) { NoticeMessageJFrame.showMessageDialogMessage(ex); } if (i == 1) {//第一行 没有必要添加\r\n allContent.append(currentAllItemInfo); } else { allContent.append("\r\n").append(currentAllItemInfo); } NoticeMessageJFrame.noticeMessage("语言:" + currentLang + "完成度:" + (i * 100 / commonContent.length) + "%|正在生成文件:" + descFile); } } try { String descFile = BuildConfigLogic.buildSingleRowStoredPath(currentLang, "", outputPath, fileName, fileName); // NoticeMessageJFrame.setCurrentProcessing(1); FileUtils.writeToFile("<?php\r\n" + allContent.toString() + "\r\n);", descFile, "UTF-8"); NoticeMessageJFrame.noticeMessage("语言:" + currentLang + "完成度:" + "100%|正在生成文件:" + descFile + "\r\n\r\n"); System.out.println("######################################################" + fileName + "100%"); } catch (FileNotFoundException ex) { NoticeMessageJFrame.noticeMessage(ex.getClass() + ":" + ex.getMessage()); } catch (IOException ex) { NoticeMessageJFrame.noticeMessage(ex.getClass() + ":" + ex.getMessage()); } } }); return currentThread; }
7
public void setDir(String d) { dir = new File(d); if (!dir.exists()) { dir.mkdirs(); } if (!dir.isDirectory()) { throw new IllegalArgumentException("Not a directory " + dir); } }
2
private int parseTimeStamps() throws MpegDecodeException, IOException { Statistics.startLog(PARSE_TIME_STAMPS); int pktLength = 0; long pts = -1, dts = -1; while( m_ioTool.nextBits( 0xFF, 8 ) ) { m_ioTool.skipBits(8); pktLength++; } if( m_ioTool.nextBits(0x1, 2) ) { m_ioTool.skipBits(16); pktLength += 2; } if( m_ioTool.nextBits(0x2, 4) ) { m_ioTool.skipBits(4); pts = m_ioTool.getBits(3) << 30; m_ioTool.skipBits(1); pts |= m_ioTool.getBits(15) << 15; m_ioTool.skipBits(1); pts |= m_ioTool.getBits(15); m_ioTool.skipBits(1); pktLength += 5; } else if( m_ioTool.nextBits(0x3, 4 ) ) { m_ioTool.skipBits(4); pts = m_ioTool.getBits(3) << 30; m_ioTool.skipBits(1); pts |= m_ioTool.getBits(15) << 15; m_ioTool.skipBits(1); pts |= m_ioTool.getBits(15); m_ioTool.skipBits(5); dts = m_ioTool.getBits(3) << 30; m_ioTool.skipBits(1); dts |= m_ioTool.getBits(15) << 15; m_ioTool.skipBits(1); dts |= m_ioTool.getBits(15); m_ioTool.skipBits(1); pktLength += 10; } else if( m_ioTool.getBits(8) != 0x0F ) { Debug.println(Debug.ERROR, "Synchronization Error"); throw new MpegDecodeException("Synchronization Error"); } else { pktLength++; } pts = (pts > 0 ) ? ( pts / 90 ) : -1; if( m_lFirstVideoPTS == -1 ) { m_lFirstVideoPTS = pts; } if( m_lFirstVideoPTS == -1 ) { m_lFirstVideoPTS = pts; } m_lLastPTS = pts; Statistics.endLog(PARSE_TIME_STAMPS); return pktLength; }
8
private void gameLoop() { try { init(); checkGLError("init"); resized(); checkGLError("resized"); long lastTime, lastFPS; lastTime = lastFPS = System.nanoTime(); int frames = 0; while (!Display.isCloseRequested() && !shouldStop()) { long deltaTime = System.nanoTime() - lastTime; lastTime += deltaTime; if (Display.wasResized()) resized(); while (Keyboard.next()) { if (Keyboard.getEventKeyState()) keyPressed(Keyboard.getEventKey(), Keyboard.getEventCharacter(), Keyboard.getEventNanoseconds()); else keyReleased(Keyboard.getEventKey(), Keyboard.getEventCharacter(), Keyboard.getEventNanoseconds()); } update(deltaTime); checkGLError("update"); render(); checkGLError("render"); Display.update(); frames++; if (System.nanoTime() - lastFPS >= 1e9) { System.out.println("FPS: ".concat(String.valueOf(frames))); lastFPS += 1e9; frames = 0; } Display.sync(fps); } } catch (Throwable exc) { exc.printStackTrace(); } finally { destroy(); } }
7
public void doTransformations() { if ((GlobalOptions.debuggingFlags & GlobalOptions.DEBUG_FLOW) != 0) GlobalOptions.err.println("before Transformation: " + this); while (lastModified instanceof SequentialBlock) { if (lastModified.getSubBlocks()[0].doTransformations()) continue; lastModified = lastModified.getSubBlocks()[1]; } while (lastModified.doTransformations()) { /* empty */ } if ((GlobalOptions.debuggingFlags & GlobalOptions.DEBUG_FLOW) != 0) GlobalOptions.err.println("after Transformation: " + this); }
5
public boolean deleteMaster(String filename, int resID) { // check for errors first if (resID == -1 || filename == null) { return false; } Object[] packet = new Object[2]; packet[0] = filename; packet[1] = myID_; // send the event super.send(super.output, 0, DataGridTags.FILE_DELETE_MASTER, new IO_data(packet, DataGridTags.PKT_SIZE, resID)); // wait for ACK int tag = DataGridTags.FILE_DELETE_MASTER_RESULT; FilterDataResult type = new FilterDataResult(filename, tag); Sim_event ev = new Sim_event(); super.sim_get_next(type, ev); boolean result = false; try { packet = (Object[]) ev.get_data(); String resName = GridSim.getEntityName(resID); int msg = ((Integer) packet[1]).intValue(); if (msg == DataGridTags.FILE_DELETE_SUCCESSFUL) { result = true; System.out.println(super.get_name() + ".deleteMaster(): " + filename + " has been deleted from " + resName); } else { System.out.println(super.get_name() + ".deleteMaster(): " + "There was an error in deleting " + filename + " from " + resName); } } catch (Exception e) { System.out.println(super.get_name() + ".masterFile(): Exception"); result = false; } return result; }
4
private void inviteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_inviteActionPerformed // TODO add your handling code here: JComboBox cb = (JComboBox) evt.getSource(); String name = (String)cb.getSelectedItem(); if ( name.equals("invite") ) { //TODO:need to fix /* for ( int i = client.onLineUsers.size() - 1; i >=0; i-- ) { boolean jump = true; for ( int j = usernames.size() - 1; j >= 0; j-- ) { if (client.onLineUsers.get(i).equals(usernames.get(j))) { jump = false; } } if (jump) { sendComboBox(client.onLineUsers.get(i)); } } for ( int i = client.onLineUsers.size() - 1; i >=0; i-- ) { boolean jump = true; for ( int j = usernames.size() - 1; j >= 0; j-- ) { if (client.onLineUsers.get(i).equals(usernames.get(j))) { jump = false; } } if (jump) { usernames.add(client.onLineUsers.get(i)); model.addElement(client.onLineUsers.get(i)); } } */ } else { boolean jump = true; for ( int i = usernames.size() - 1; i >= 0; i-- ) { if (usernames.get(i).equals(name)) { jump = false; } } if (jump) { sendComboBox(name); usernames.add(name); model.addElement(name); } } }//GEN-LAST:event_inviteActionPerformed
4
public static Vector add(Vector op1, Vector op2) throws DimensionMismatchException { if (op1.getDimension() != op2.getDimension()) { throw new DimensionMismatchException(); } Vector result = new Vector(op1.getDimension()); for (int i = 0; i < result.getDimension(); i++){ result.setComponent(i, op1.getComponent(i)+op2.getComponent(i)); } return result; }
2
public boolean testFr(LinkedList<String> dico, int[] alphabet, String test, String mot){ int bInf, bSup; ListIterator<String> i; if(!(test.length()!=7 || test.charAt(0)!=mot.charAt(0))){ bInf=alphabet[test.charAt(0)-'a']; bSup=dico.size(); if(test.charAt(0)!='z') bSup=alphabet[test.charAt(0)-('a'-1)]; i=dico.listIterator(bInf); while(bInf<bSup){ if(test.equals(i.next())) return true; bInf++; } } return false; }
5
int depth() { if (parent != null) { return 1 + parent.depth(); } return 1; }
1
public void actionPerformed(ActionEvent e) { //this. }
0
public Widget createWidget(Composite parent, int style) { String tooltip = getTooltip(); GridData controlGD = new GridData( SWT.FILL, SWT.CENTER, false, false ); // label if ( control.getLabel() != null ) { label = new Label( parent, SWT.NONE ); label.setText( control.getLabel() ); if ( tooltip != null ) label.setToolTipText( tooltip ); controlGD.horizontalSpan = 1; } else { controlGD.horizontalSpan = 2; } // dropDownList style = style | SWT.BORDER; if ( control instanceof DropDownListT ) { style |= SWT.READ_ONLY; } dropDownList = new Combo( parent, style ); dropDownList.setLayoutData( controlGD ); // dropDownList items java.util.List<ListItemT> listItems = ( control instanceof EditableDropDownListT ) ? ( (EditableDropDownListT) control ).getListItem() : ( (DropDownListT) control ).getListItem(); // TODO: throw error if there are no list items for ( ListItemT listItem : listItems ) dropDownList.add( listItem.getUiRep() ); // tooltip if ( tooltip != null ) dropDownList.setToolTipText( tooltip ); // default initializer dropDownList.select( 0 ); // select initValue if available String initValue = (String) ControlHelper.getInitValue( control, getAtdl4jOptions() ); if ( initValue != null ) setValue( initValue, true ); return parent; }
7
@Override public String toString() { StringBuilder string = new StringBuilder(); string.append(super.toString()); if (this.journal != null) string.append("Journal: ").append(this.journal).append("\n"); if (this.volume != null) string.append("Volume: ").append(this.volume).append("\n"); if (this.number != null) string.append("Number: ").append(this.number).append("\n"); if (this.pages != null) string.append("Pages: ").append(this.pages).append("\n"); return string.toString(); }
4
public static boolean isCompressedPath(String path) { path = path.trim().toLowerCase(); return path.endsWith(DataConstants.CATALOGUE_COMPRESSED_FILE_EXTENSION) || path.endsWith(DataConstants.CATALOGUE_COMPRESSED_FILE_EXTENSION_OLD) || path.endsWith(DataConstants.GAME_SYSTEM_COMPRESSED_FILE_EXTENSION) || path.endsWith(DataConstants.GAME_SYSTEM_COMPRESSED_FILE_EXTENSION_OLD) || path.endsWith(DataConstants.ROSTER_COMPRESSED_FILE_EXTENSION) || path.endsWith(DataConstants.ROSTER_COMPRESSED_FILE_EXTENSION_OLD) || path.endsWith(DataConstants.INDEX_COMPRESSED_FILE_EXTENSION); }
6
public void render(Graphics g) { g.setColor(Color.red); g.drawString(currentPlayer.name+"'s Turn", 30, 30); g.setColor(Color.blue); g.drawString("Playing State: "+playingStateNames[playingState], 30, 50); //g.drawString("Change State\nM = Moving\nS = Shooting\nB = Buying", 30, 50); // for (int x = 7; x < MainFinesse.width / 32 + 1; x++) { // for (int y = 0; y < (MainFinesse.height / 32) + 1; y++) { // g.fillRect(x * 32, y * 32, 31, 31); // } // } for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { mapArray[i][j].render(g); } } if(currentMinionTile != null && playingState == SHOOTING){//Shooting g.setColor(Color.red); g.setLineWidth(5); int circleX = currentMinionTile.x + currentMinionTile.width / 2 - shootingDiameter / 2; int circleY = currentMinionTile.y + currentMinionTile.height / 2 - shootingDiameter / 2; g.drawOval(circleX, circleY, shootingDiameter, shootingDiameter); } if (bullet != null) { bullet.render(g); } if(playingState == POPUP){ g.setColor(new Color(0,0,200,0.9f)); g.fillRect(popupX,popupY,popupWidth,popupHeight); g.setFont(bigFont); g.setColor(Color.yellow); int stringWidth = bigFont.getWidth(popupMessage); g.drawString(popupMessage, popupX + (popupWidth - stringWidth) / 2, popupY+50); stringWidth = bigFont.getWidth("This is an alert, click to remove"); g.drawString("This is an alert, click to remove", popupX + (popupWidth - stringWidth) / 2, popupY+300); } // g.drawImage(testImage, 20, 20); // g.setColor(new Color(255,0,0,0.2f)); // g.fillRect(20, 20, 20, 20); // g.fillRect(80, 20, 20, 20); // g.fillRect(20, 80, 20, 20); // g.fillRect(80, 80, 20, 20); // g.setColor(Color.black); // for(int i = 0;i<4;i++){ // for(int j = 0;j<4;j++){ // g.drawRect(20+i*20, 20+j*20, 20, 20); // } // } }
6
XmlWriter writeEntity(String name) throws IOException { closeOpeningTag(true); this.closed = false; for (int tabIndex = 0; tabIndex < stack.size() + indentingOffset; tabIndex++) this.writer.write(INDENT_STRING); this.writer.write("<"); this.writer.write(name); stack.add(name); this.empty = true; this.justWroteText = false; return this; }
1
public void mouseMoved(int x, int y) { if ((x >= theComponent.getX()) && ((x <= (theComponent.getX() + buttonWidth)))) { if ((y >= theComponent.getY()) && (y <= (theComponent.getY() + buttonHeight))) { if ((y > theComponent.getY()) && (y < (theComponent.getY() + buttonHeight))) { isMouseOver = true; } else { isMouseOver = true; } } else { isMouseOver = false; } } else { isMouseOver = false; } }
6
@Override public final IoBuffer compact() { int remaining = remaining(); int capacity = capacity(); if (capacity == 0) { return this; } if (isAutoShrink() && remaining <= capacity >>> 2 && capacity > minimumCapacity) { int newCapacity = capacity; int minCapacity = Math.max(minimumCapacity, remaining << 1); for (;;) { if (newCapacity >>> 1 < minCapacity) { break; } newCapacity >>>= 1; } newCapacity = Math.max(minCapacity, newCapacity); if (newCapacity == capacity) { return this; } // Shrink and compact: //// Save the state. ByteOrder bo = order(); //// Sanity check. if (remaining > newCapacity) { throw new IllegalStateException( "The amount of the remaining bytes is greater than " + "the new capacity."); } //// Reallocate. ByteBuffer oldBuf = buf(); ByteBuffer newBuf = getAllocator().allocateNioBuffer(newCapacity, isDirect()); newBuf.put(oldBuf); buf(newBuf); //// Restore the state. buf().order(bo); } else { buf().compact(); } mark = -1; return this; }
8
public void setName(String name) { Name = name; }
0
public void loadXML ( ) { JFileChooser chooser = new JFileChooser(); chooser.setFileSelectionMode( JFileChooser.FILES_ONLY ); chooser.setAcceptAllFileFilterUsed( false ); chooser.addChoosableFileFilter( new XMLFileFilter() ); int option = chooser.showOpenDialog( MenuApp.getFrame() ); if ( option == JFileChooser.APPROVE_OPTION ) { // clicked Save File f = chooser.getSelectedFile(); System.out.println( "Chose file: " + f.getAbsolutePath() ); FileReader fr; try { // open the file fr = new FileReader( f ); BufferedReader in = new BufferedReader( fr ); // parse through XML file handler LoadXMLHandler xf = new LoadXMLHandler(); if ( parseXML( xf, in ) ) { // successful parsing // save the menu setMenuQuantity( xf.getMenuQuantity() ); for ( int i = 1; i <= xf.getMenuQuantity(); i++ ) { setMenuLabel( i, xf.getLabel( i ) ); setMenuCode( i, xf.getCode( i ) ); } // reload the menu MenuApp.getFrame().resetMenuLabelAndCode(); MenuApp.getFrame().resetMenuEntryList(); MenuApp.getFrame().setMenuQuantity( xf.getMenuQuantity() ); } if ( in != null ) { in.close(); } if ( fr != null ) { fr.close(); } } catch ( FileNotFoundException e ) { e.printStackTrace(); } catch ( IOException e ) { e.printStackTrace(); } } }
7
public static void postorder(TreeNode root) { if (root == null) return; Stack<TreeNode> S = new Stack<TreeNode>(); S.push(root); TreeNode previous = null; while (!S.empty()) { //get the current node from the stack TreeNode current = S.peek(); //going down the tree if (previous == null || previous.left == current || previous.right ==current) { if (current.left != null) S.push(current.left); else if (current.right != null) S.push(current.right); else { current.print(); S.pop(); } } // left sub tree is traversed else if (current.left == previous) { if (current.right != null) S.push(current.right); else { current.print(); S.pop(); } } //both subtrees are processed else { current.print(); S.pop(); } previous = current; } //end of while System.out.println(); }
9
private void gameThread() { running = true; try { long beginTime = System.nanoTime(); double previousDelta = 0.0; boolean runningSlowly = false; while(running) { if(interval <= 0) throw new Error("GameTimer interval must be >= 0."); long frameStartTime = System.nanoTime(); double givenDelta = capDelta ? Math.min(previousDelta, interval) : previousDelta; // works out the (maybe) capped delta tickHandler.tick( givenDelta, (double)(frameStartTime - beginTime) / 1e+9, runningSlowly); long frameDeltaTime = System.nanoTime() - frameStartTime; double runningTime = (double)(frameDeltaTime) / 1e+9; long sleepTime = (long)(interval * 1e+9) - frameDeltaTime; runningSlowly = sleepTime < 0; if(runningTime < interval) { if(sleepTime >= 100000) { // only sleep if sleepTime's not too small Thread.sleep( sleepTime / 1000000l, (int)(sleepTime % 1000000l)); } } previousDelta = (double) (System.nanoTime() - frameStartTime) / 1e+9; } } catch(InterruptedException e) { // ok } catch(Exception e) { errorHandler.handle(e); } finally { cleanupHandler.cleanup(); } }
7
public static void main(String args[]){ String objectListPath = "/u/ml/mindseye/nlg_lm/LM/lesk_syns_purdue.txt"; int no_objects = readObjectList(objectListPath); String outputMatrixPath = "/u/ml/mindseye/nlg_lm/LM/object_count.txt"; int[] object_counts = new int[no_objects]; String ldcCorpusPath = "/scratch/cluster/niveda/extracted_original"; File input_folder = new File(ldcCorpusPath); Stack<File> stack = new Stack<File>(); stack.push(input_folder); int x=1; try{ while (!stack.isEmpty()) { File child = stack.pop(); if (child.isDirectory()) { for (File f : child.listFiles()) stack.push(f); } else if (child.isFile()) { System.out .println("Processing: " + child.getAbsolutePath()); FileReader fr = new FileReader(child.getAbsolutePath()); BufferedReader br = new BufferedReader(fr); String readLine = ""; while ((readLine = br.readLine()) != null) { String words[] = readLine.split("\\s+"); for(int i=0;i<words.length;i++){ if(object_words.containsKey(words[i])) object_counts[object_words.get(words[i])]+=1; } } br.close(); fr.close(); } } FileWriter fw = new FileWriter(outputMatrixPath); fw.write("[OBJECT_COUNTS]\n"); for (int i = 0; i < no_objects; i++) { fw.write(object_counts[i]+"\t"); } fw.close(); } catch(Exception e){ System.out.println("Exception caught:"+e); e.printStackTrace(); } }
9
private static void readFragmentsEnc(Stream buffer) { Censor.anIntArray620 = new int[buffer.getInt()]; for (int i = 0; i < Censor.anIntArray620.length; i++) { Censor.anIntArray620[i] = buffer.getUnsignedShort(); } }
1
public void tick(Input input, double delta) { if (isReady[0] && !isReady[1]) { delta = 0; isReady[1] = true; } physicHandler.tick(input, delta); for (int i = 0; i < entities.size(); i++) { AbstractEntity e = entities.get(i); for (int j = 0; j < entities.size() && e.isInteractsWithWorld() && e.getType() != AbstractEntity.PIXEL; j++) { AbstractEntity o = entities.get(j); if (o.isInteractsWithWorld() && e.intersects(o)) { e.collided(o); } } for (ITrigger element : getTriggers()) { element.triggers(e); } e.beforeTick(delta); e.tick(input, delta); e.afterTick(delta); } }
9
public void drawCollidableObjects(){ for(collidableObject tempObj : listWrecks){ tempObj.display(); } }
1
@SuppressWarnings("serial") public MyTable() { data = new Object[30][5]; for (int i = 0; i < 30; i++) { data[i][0] = new Boolean(false); data[i][1] = "Column " + i; data[i][2] = (Math.random() > 0.5) ? new ImageIcon( JTableRenderer.class.getResource(IMAGE_PATH + "preferences.gif")) : null; data[i][3] = (Math.random() > 0.5) ? new ImageIcon( JTableRenderer.class.getResource(IMAGE_PATH + "preferences.gif")) : null; data[i][4] = (Math.random() > 0.5) ? new ImageIcon( JTableRenderer.class.getResource(IMAGE_PATH + "preferences.gif")) : null; } setModel(createModel()); setTableHeader(null); setAutoscrolls(true); setGridColor(Color.WHITE); TableColumn column = getColumnModel().getColumn(0); column.setMaxWidth(20); column = getColumnModel().getColumn(2); column.setMaxWidth(12); column = getColumnModel().getColumn(3); column.setMaxWidth(12); column = getColumnModel().getColumn(4); column.setMaxWidth(12); setTransferHandler(new TransferHandler() { /* (non-Javadoc) * @see javax.swing.TransferHandler#getSourceActions(javax.swing.JComponent) */ @Override public int getSourceActions(JComponent c) { return COPY_OR_MOVE; } /* * (non-Javadoc) * * @see javax.swing.TransferHandler#createTransferable(javax.swing.JComponent) */ protected Transferable createTransferable(JComponent c) { sourceRow = getSelectedRow(); dragSource = JTableRenderer.this; //mxRectangle bounds = new mxRectangle(0, 0, MyTable.this // .getWidth(), 20); return new mxGraphTransferable(null, null, null); } }); setDragEnabled(true); setDropTarget(new DropTarget(this, // component DnDConstants.ACTION_COPY_OR_MOVE, // actions this)); setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); }
4
public void cmdQuote(CommandSender sender, String[] args) { if(args.length != 3) { sender.sendMessage(Conf.colorMain + "Usage:"); sender.sendMessage(Conf.colorAccent + "/ee quote <quantity> <material name>"); return; } int quantity = 0; Material material; try { quantity = Integer.parseInt(args[1]); } catch( Exception e ) { sender.sendMessage(Conf.colorWarning + "Invalid quantity"); return; } if(quantity <= 0) { sender.sendMessage(Conf.colorWarning + "Please enter a quantity greater than 0"); return; } material = materials.get(args[2]); if( material == null ) { sender.sendMessage(Conf.colorWarning + "Invalid material"); return; } Market market = markets.get(material); int offerQuantity = market.getOffersQuantity(); double offerPrice = market.getOfferPrice(quantity); double bidPrice = market.getBidPrice(quantity); int bidQuantity = market.getBidsQuantity(); if(offerQuantity == 0) { sender.sendMessage(Conf.colorMain + "No " + args[2] + " is available."); } else if(quantity < offerQuantity) { sender.sendMessage(Conf.colorAccent + "" + quantity + " " + Conf.colorMain + args[2] + " is available for " + Conf.colorAccent + "" + offerPrice); } else { sender.sendMessage(Conf.colorAccent + "" + offerQuantity + " " + Conf.colorMain + args[2] + " is available for " + Conf.colorAccent + offerPrice); } if(bidQuantity == 0) { sender.sendMessage(Conf.colorMain + "No " + args[2] + " is wanted."); } else if(quantity < bidQuantity) { sender.sendMessage(Conf.colorAccent + "" + quantity + " " + Conf.colorMain + args[2] + " is wanted for " + Conf.colorAccent + bidPrice); } else { sender.sendMessage(Conf.colorAccent + "" + bidQuantity + " " + Conf.colorMain + args[2] + " is wanted for " + Conf.colorAccent + bidPrice); } }
8
public void click(int mouseX, int mouseY) { for (MenuItem item : this.itemList) { if (item.check(mouseX, mouseY)) { item.action(); return; } } }
2
public void setOccupant(Peuple occupant) { this.occupant = occupant; int tour = Partie.getInstance().getTourEnCours(); List<Peuple> ls; if (tour < this.prisesDuTerritoire.size()) { ls = this.prisesDuTerritoire.get(tour); } else { ls = new ArrayList<Peuple>(); int s = this.prisesDuTerritoire.size(); for (; s < tour; s++) { this.prisesDuTerritoire.add(null); } this.prisesDuTerritoire.add(ls); } ls.add(occupant); }
2
public void keyReleased(KeyEvent e) { int key = e.getKeyCode(); if (key == KeyEvent.VK_LEFT) { dx = 0; } if (key == KeyEvent.VK_RIGHT) { dx = 0; } if (key == KeyEvent.VK_UP) { dy = 0; } if (key == KeyEvent.VK_DOWN) { dy = 0; } }
4
public static void render( float scale, float rotation, Vec3D offset, FloatBuffer vertBuffer, FloatBuffer normBuffer, FloatBuffer textBuffer, int numFacets ) { GL11.glMatrixMode(GL11.GL_MODELVIEW) ; GL11.glLoadIdentity() ; if (numFacets < 1) numFacets = vertBuffer.capacity() / VFP ; if (offset != null) GL11.glTranslatef(offset.x, offset.y, offset.z) ; else GL11.glTranslatef(0, 0, 0) ; GL11.glRotatef(rotation, 0, 0, 1) ; GL11.glScalef(scale, scale, scale) ; // // Only set the texture buffer if one has been provided: if (textBuffer == null) { GL11.glDisable(GL11.GL_TEXTURE_2D) ; GL11.glDisableClientState(GL11.GL_TEXTURE_COORD_ARRAY) ; } else { GL11.glEnable(GL11.GL_TEXTURE_2D) ; GL11.glEnableClientState(GL11.GL_TEXTURE_COORD_ARRAY) ; GL11.glTexCoordPointer(2, 0, textBuffer) ; } // // And only set the normal buffer if one has been provided: if (normBuffer == null) GL11.glDisableClientState(GL11.GL_NORMAL_ARRAY) ; else { GL11.glEnableClientState(GL11.GL_NORMAL_ARRAY) ; GL11.glNormalPointer(0, normBuffer) ; } // // Bind the vertex buffer and render- GL11.glVertexPointer(3, 0, vertBuffer) ; GL11.glDrawArrays(GL11.GL_TRIANGLES, 0, numFacets * 3) ; }
4
public void testNullForkStack() throws Exception { fc1=new ForkChannel(a, "stack", "fc1"); fc2=new ForkChannel(a, "stack", "fc2"); MyReceiver<Integer> r1=new MyReceiver<>(), r2=new MyReceiver<>(); fc1.setReceiver(r1); fc2.setReceiver(r2); a.connect(CLUSTER); fc1.connect("foo"); fc2.connect("bar"); for(int i=1; i <= 5; i++) { fc1.send(null, i); fc2.send(null, i+5); } List<Integer> l1=r1.list(), l2=r2.list(); for(int i=0; i < 20; i++) { if(l1.size() == 5 && l2.size() == 5) break; Util.sleep(500); } System.out.println("r1: " + r1.list() + ", r2: " + r2.list()); assert r1.size() == 5 && r2.size() == 5; for(int i=1; i <= 5; i++) assert r1.list().contains(i) && r2.list().contains(i+5); }
7
public void setMaxFailedAttempts(Long value) { this.maxFailedAttempts = value; }
0
protected void rotateTurn() { if (currentTurn < playerCount) { currentTurn += 1; PrimaryController.generateNotification("Switching to Player " + currentTurn, 0); turnTimer.setRepeats(true); percent = 0; turnTimer.start(); } else { for (int r = 0; r < unitsP1.length; r++) { for (int c = 0; c < unitsP1.length; c++) { if (unitsP1[r][c].toInt() != 0) { activityQueue.add(unitsP1[r][c].getActivityList()); } if (unitsP2[r][c].toInt() != 0) { activityQueue.add(unitsP2[r][c].getActivityList()); } if (unitsP3[r][c].toInt() != 0) { activityQueue.add(unitsP3[r][c].getActivityList()); } if (unitsP4[r][c].toInt() != 0) { activityQueue.add(unitsP4[r][c].getActivityList()); } } } activityQueue.process(); // Consider how to implement the chain of activities currentTurn = 1; } waitingState = 1; }
7
@Override public void actionPerformed(ActionEvent e) { OutlinerDocument doc = (OutlinerDocument) Outliner.documents.getMostRecentDocumentTouched(); OutlinerCellRendererImpl textArea = doc.panel.layout.getUIComponent(doc.tree.getEditingNode()); if (textArea == null) { return; } Node node = textArea.node; JoeTree tree = node.getTree(); OutlineLayoutManager layout = tree.getDocument().panel.layout; if (doc.tree.getComponentFocus() == OutlineLayoutManager.TEXT) { RightAction.moveRightText(textArea, tree, layout); } else if (doc.tree.getComponentFocus() == OutlineLayoutManager.ICON) { RightAction.moveRight(tree, layout); } }
3
public void SetTicks(int ticks) { this.ticks = ticks; }
0
private void add(Method method) { // Check for annotation ICallbackEnum message = getMethodMessage(method); if(message == null) return; // Check Parameters Class<?>[] params = method.getParameterTypes(); Class<?> metaClass = message.getMetadataClass(); if(metaClass == null) metaClass = IJeTTSession.class; if(params.length != 1 || params[0] != metaClass) { // Warn and return if(JeTT.isDebugging()) System.err.format("WARNING: Ignoring method '%s.%s' marked as %s callback; must have parameters: %s\n", method.getDeclaringClass(), method.getName(), message.name(), metaClass.getCanonicalName() ); return; } // Bind MethodParamBinding binding = new MethodParamBinding(method, message); // Check for existence if(!this.methods.containsKey(message)) // Add this.methods.put(binding, method); }
8
public static double sum(double[] vals) { double sum = 0; for (double v : vals) { sum = sum + v; } return sum; }
1
public Transition<ET, ?> nextChainedTransition(State<ET> inputState, Event<?> event, ET entity) throws FiniteStateException { if (!initialized) throw new FiniteStateException( "State map not yet initialized through call to build() method"); State matchingState = inputState; boolean noMatcher = true; Transition<ET, ?> transition = null; // Walk the state hierarchy looking for a transition that accepts this // event. while (matchingState != null) { TransitionMatcher<ET> matcher = transitionMap.get(matchingState); if (matcher != null) { noMatcher = false; transition = matcher.matchTransition(event, entity); if (transition != null) break; } matchingState = matchingState.getParent(); } // Could not find any transitions from this state. if (noMatcher) { throw new TransitionNotFoundException( "No exit transitions from state", inputState, event, entity); } if (transition == null) { throw new TransitionNotFoundException( "No matching exit transition found", inputState, event, entity); } return transition; }
9
@Override public void validate() { if (platform == null) { addActionError("Please Select Platorm"); } if (location == null) { addActionError("Please Select Location"); } if (iphone.equals("Please select")) { addActionError("Please Select Os"); } if (gender == null) { addActionError("Please Select Gender"); } if (age == null) { addActionError("Please Select Age"); } }
5
public double[][] getComponents() { double[][] values = new double[3][3]; for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) values[i][j] = m[i][j]; return values; }
2
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Product product = (Product) o; return number == product.number && !(name != null ? !name.equals(product.name) : product.name != null); }
5
private void log( Level level, String msg, Throwable ex ) { if( getLogger().isLoggable(level) ) { LogRecord record = new LogRecord(level, msg); if( !classAndMethodFound ) { getClassAndMethod(); } record.setSourceClassName(sourceClassName); record.setSourceMethodName(sourceMethodName); if( ex != null ) { record.setThrown(ex); } getLogger().log(record); } }
3
public static void loadPreset_HelpMenu_ComparePins(final Container mainFrame) { ArtAssets art = ArtAssets.getInstance(); PinLoader pinLoader = PinLoader.getInstance(); BackgroundPanel pane = new BackgroundPanel(art.getAsset(ArtAssets.IN_GAME_BACKGROUND)); //Set up the menu buttons pane.setLayout(null); MenuButton backButton = new MenuButton("Back", art.getAsset(ArtAssets.MENU_BUTTON_LARGE), pane); MenuButton doneButton = new MenuButton("Done", art.getAsset(ArtAssets.MENU_BUTTON_LARGE), pane); backButton.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { mainFrame.removeAll(); loadPreset_HelpMenu_Explanation(mainFrame); mainFrame.validate(); mainFrame.repaint(); } }); doneButton.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { mainFrame.removeAll(); loadPreset_MainMenu(mainFrame); mainFrame.validate(); mainFrame.repaint(); } }); backButton.setBounds(200,400,100,55); backButton.addText(20); pane.add(backButton); doneButton.setBounds(350,400,100,55); doneButton.addText(20); pane.add(doneButton); JLabel contextLabel = new JLabel( "<html><body><p style=\"font-size:14px\">Here are all the pins in the game. Study them carefully to spot the differences!</p></body></html>" ); contextLabel.setBounds(50,0,550,120); contextLabel.setForeground(new Color(252, 90, 90)); pane.add(contextLabel); ExamplePin examplePin; int pinNumber = 0; for (int y = 0; y < 4; y++) { for (int x = 0; x < 8; x++) { if (pinNumber < 58) { //There are only 29 pins currently, each with one scrapper, for a total of 58. Ignore the remaining loop iterations past the 58th pin examplePin = new ExamplePin( pinLoader.getPin(pinNumber), pinLoader.getPin(pinNumber + 1), pane ); examplePin.setBounds( 35 + (x * 70), //X 100 + (y * 70), //Y 70, //Width 70 //Height ); pane.add(examplePin); } pinNumber = pinNumber + 2; } } //Add the finished panel to our main JFrame mainFrame.add(pane); }
3
public String getName() { return name; }
0
@Override public void actionPerformed(ActionEvent e) { if(e.getSource() == logOff){ frameRef.setContentPane(new Login(frameRef)); } if(e.getSource() == searchItems){ contentPanelLayout.show(panel, "searchItems"); } if(e.getSource() == searchBooks){ contentPanelLayout.show(panel, "searchBooks"); } if(e.getSource() == borrowedItems){ contentPanelLayout.show(panel, "borrowedItems"); } if(e.getSource() == borrowedBooks){ contentPanelLayout.show(panel, "borrowedBooks"); } if(e.getSource() == reservedBooks){ contentPanelLayout.show(panel, "reservedBooks"); } if(e.getSource() == reservedItems){ contentPanelLayout.show(panel, "reservedItems"); } }
7
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed String frek=jTextField8.getText(); String put="C:\\Users\\vhailor\\Documents\\NetBeansProjects\\JavaApplication10\\"; DecimalFormat f = new DecimalFormat("##"); DecimalFormat f1 = new DecimalFormat("##.##"); String duz1=jTextField1.getText(); String sir1=jTextField2.getText(); String duz2=jTextField3.getText(); String sir2=jTextField4.getText(); String v1=jTextField9.getText(); String v2=jTextField10.getText(); float visAnt1=Float.valueOf(v1); float visAnt2=Float.valueOf(v2); double du1=Double.valueOf(duz1); double si1=Double.valueOf(sir1); double du2=Double.valueOf(duz2); double si2=Double.valueOf(sir2); float antVis1=Float.valueOf(jTextField9.getText()); float antVis2=Float.valueOf(jTextField10.getText()); String d1=String.valueOf(f.format(Math.floor(du1))); String s1=String.valueOf(f.format(Math.floor(si1))); String d2=String.valueOf(f.format(Math.floor(du2))); String s2=String.valueOf(f.format(Math.floor(si2))); String nazivDat=""; nazivDat+=put+"N"+d1+"E"; if(si1<100) nazivDat+="0"; nazivDat+=s1+".hgt"; //File file = new File("C:\\Users\\vhailor\\Documents\\NetBeansProjects\\JavaApplication10\\N40E014.hgt"); File file = new File(nazivDat); try{ RandomAccessFile raf = new RandomAccessFile(file, "rw"); GetData dat=new GetData(raf); int broj=0; double udaljenost=Math.abs(distance(du1,si1,du2,si2)); double max=0;//MAX fresnel double maxFres=0; double fresnel,fresnelPlot; double rez,rezLos,rez1,rezPoc,rezKraj; int count=0; double razX=0,razY=0,razT; double dista1,dista2; double lambda=0.3/Double.parseDouble(frek);//frek u GHz --> lambda u m !!!!!!!!!!! double duljinaTrase=distance(du1,si1,du2,si2); int brUzoraka=10000; rezPoc=dat.getElevationFor(du1, si1)+visAnt1; rezKraj=dat.getElevationFor(du2, si2)+visAnt2; rezLos=Math.abs((dat.getElevationFor(du1, si1)+visAnt1)-(dat.getElevationFor(du2, si2)+visAnt2)); while(count<=brUzoraka){ razX=Math.abs(du1-du2)/brUzoraka; razY=Math.abs(si1-si2)/brUzoraka; razT=duljinaTrase/brUzoraka; rez=dat.getElevationFor(du1+(razX*count), si1+(razY*count)); dista1=Math.abs(distance(du1,si1,du1+(razX*count),si1+(razY*count))); dista2=Math.abs(distance(du2,si2,du1+(razX*count),si1+(razY*count))); fresnel=1000*Math.sqrt((dista1*dista2*(lambda/1000))/(udaljenost));//fresnel radius if(fresnel>maxFres){ maxFres=fresnel; } count++; } count=0; while(count<=brUzoraka){ razX=Math.abs(du1-du2)/brUzoraka; razY=Math.abs(si1-si2)/brUzoraka; razT=duljinaTrase/brUzoraka; rez=dat.getElevationFor(du1+(razX*count), si1+(razY*count)); dista1=Math.abs(distance(du1,si1,du1+(razX*count),si1+(razY*count))); dista2=Math.abs(distance(du2,si2,du1+(razX*count),si1+(razY*count))); fresnel=1000*Math.sqrt((dista1*dista2*(lambda/1000))/(udaljenost));//fresnel radius rez1=rezPoc+(count*rezLos/brUzoraka); fresnelPlot=-Math.sqrt(dista1*dista1+fresnel*fresnel)-Math.sqrt(dista2*dista2+fresnel*fresnel)-udaljenost+rez1; //krivulja if(0.1*(maxFres+rez)>fresnelPlot){ broj++; } //System.out.println(broj +" "+ dista1); count++; } if(broj>0){ jLabel11.setVisible(true); jLabel12.setVisible(false); } else { jLabel11.setVisible(false); jLabel12.setVisible(true); } } catch(IOException e){ JOptionPane.showMessageDialog(rootPane, e.getMessage()); } }//GEN-LAST:event_jButton3ActionPerformed
7
private boolean uhattuOikealta(int pelaajaNumero, int x, int y) { int i = 1; while(y+i < 8 && kentta[x][y+i].onTyhja()) i++; if(y+i == 8) return false; if(kentta[x][y+i].getNappula().omistajanPelinumero() != pelaajaNumero) { if(i == 1 && kentta[x][y+i].getNappula().getClass() == new Kuningas().getClass()) return true; if(kentta[x][y+i].getNappula().getClass() == new Kuningatar().getClass()) return true; if(kentta[x][y+i].getNappula().getClass() == new Torni().getClass()) return true; } return false; }
8
@Test public void test() { Imagem img; ImagemIterator iterator = new SuperiorDiagonalIterator(); // Teste com largura maior i = 0; img = new Imagem(4, 3); iterator.iterate(img, new ImageIteratorCallback() { @Override public void callback(int x, int y) { switch(i) { case 0: assertPosition(0, 0, x, y); break; case 1: assertPosition(1, 1, x, y); break; case 2: assertPosition(2, 2, x, y); break; case 3: assertPosition(3, 2, x, y); break; default: Assert.fail(); } i++; } }); // Teste com altura maior i = 0; img = new Imagem(3, 4); iterator.iterate(img, new ImageIteratorCallback() { @Override public void callback(int x, int y) { switch(i) { case 0: assertPosition(0, 0, x, y); break; case 1: assertPosition(1, 1, x, y); break; case 2: assertPosition(2, 2, x, y); break; case 3: assertPosition(2, 3, x, y); break; default: Assert.fail(); } i++; } }); }
8
public void extractFeature(List<Article> artList, boolean isTraining) { HashMap<Article, SentencePOS[]> allPos = new HashMap<Article, MophoFeatureExtractor.SentencePOS[]>(); // load all short article POS tags with article id for (int i = 0; i < artList.size(); i++) { System.out.println(i); Article art = artList.get(i); // if (art.getSentenceCount() > THRESH_HOLD // || art.getSentenceCount() == 0) { // // run only on short articles // continue; // } SentencePOS[] sentPos = new SentencePOS[art.getSentences().size()]; allPos.put(art, sentPos); for (int j = 0; j < art.getSentences().size(); j++) { sentPos[j] = SentencePOS .calculatePos(art.getSentences().get(j)); } } String outFileName = "morph-feature-" + new Date().getTime() + ".txt"; String outPath = Pipeline.prop.getProperty("feature.folder"); PrintWriter out = null; try { out = new PrintWriter(new FileWriter(outPath + "/" + outFileName)); // extract POS features for (Entry<Article, SentencePOS[]> entry : allPos.entrySet()) { StringBuilder sb = new StringBuilder(); for (MorphFeaturesCalculator calc : calcs) { sb.append(calc.calculateFeature(entry) + "\t"); } if (isTraining) { sb.append(entry.getKey().getLabel()); } out.println(sb.toString()); } } catch (IOException ioe) { ioe.printStackTrace(); } finally { if (out != null) { out.flush(); out.close(); } out = null; } }
7
private static String initialise(Token currentToken, int[][] expectedTokenSequences, String[] tokenImage) { String eol = System.getProperty("line.separator", "\n"); StringBuffer expected = new StringBuffer(); int maxSize = 0; for (int i = 0; i < expectedTokenSequences.length; i++) { if (maxSize < expectedTokenSequences[i].length) { maxSize = expectedTokenSequences[i].length; } for (int j = 0; j < expectedTokenSequences[i].length; j++) { expected.append(tokenImage[expectedTokenSequences[i][j]]).append(' '); } if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) { expected.append("..."); } expected.append(eol).append(" "); } String retval = "Encountered \""; Token tok = currentToken.next; for (int i = 0; i < maxSize; i++) { if (i != 0) retval += " "; if (tok.kind == 0) { retval += tokenImage[0]; break; } retval += " " + tokenImage[tok.kind]; retval += " \""; retval += add_escapes(tok.image); retval += " \""; tok = tok.next; } retval += "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn; retval += "." + eol; if (expectedTokenSequences.length == 1) { retval += "Was expecting:" + eol + " "; } else { retval += "Was expecting one of:" + eol + " "; } retval += expected.toString(); return retval; }
8
private void processInventory() { ArrayList<InventoryListObject> inventoryLists; Iterator<InventoryListObject> inventoryListObjectsIter; InventoryListObject inventoryListObject; ArrayList<InventoryItemObject> inventoryItemList; String listName; InventoryPanel inventoryPanel; _inventoryObjects = InventoryObjectDAO.getInventoryObject(); if ( _inventoryObjects != null ) { inventoryLists = _inventoryObjects.getInventorysLists(); inventoryListObjectsIter = inventoryLists.iterator(); while ( inventoryListObjectsIter.hasNext() ) { inventoryListObject = (InventoryListObject) inventoryListObjectsIter.next(); if ( inventoryListObject != null ) { listName = inventoryListObject.getListName(); //System.out.println( "List Name: " + listName ); // DEV ListName inventoryItemList = inventoryListObject.getInventorysItems(); inventoryPanel = new InventoryPanel( listName, inventoryItemList ); tpContent.addTab( listName, null, inventoryPanel ); inventoryPanel.processInventory(); } // if } // while } // if } // processInventory --------------------------------------------------------
3
@Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof DefaultSettings)) return false; DefaultSettings that = (DefaultSettings) o; if (!age.equals(that.age)) return false; if (!email.equals(that.email)) return false; if (!name.equals(that.name)) return false; return true; }
5
public void pushWeights(Map<Object, Integer> weightedItems) { for (Map.Entry<Object, Integer> weightedItem : weightedItems.entrySet()) { String key = createKey(weightedItem.getKey()); if (sharedWeights.containsKey(key)) { // could add another heuristic here, for how to mix the new values with the current ones on push sharedWeights.put(key, weightedItem.getValue()); } else { sharedWeights.put(key, weightedItem.getValue()); } } if (hasBeenOriginallyDeviated == false) { originalDeviationStrategy.deviate(sharedWeights); hasBeenOriginallyDeviated = true; } }
3