text
stringlengths
14
410k
label
int32
0
9
public void setVoltageColor(Graphics g, double volts) { if (needsHighlight()) { g.setColor(selectColor); return; } if (!sim.isShowingVoltage()) { if (!sim.isShowingPowerDissipation()) // && !conductanceCheckItem.getState()) { g.setColor(whiteColor); } return; } int c = (int) ((volts + sim.getVoltageRange()) * (colorScaleCount - 1) / (sim.getVoltageRange() * 2)); if (c < 0) { c = 0; } if (c >= colorScaleCount) { c = colorScaleCount - 1; } if (sim.isStopped()) { g.setColor(Color.decode("#3E80BD"));//blue g.setColor(Color.white);//blue } else { g.setColor(colorScale[c]); } }
6
void resampleProcess() throws FileNotFoundException{ //Scan entries in the index java.util.Iterator<Entry<String, long[]>> iter = index.entrySet().iterator(); long conNo ; int evictCount=0; while(iter.hasNext()){ entryCount++; long meta[] = iter.next().getValue(); if(meta[0]<=threshold && evictCount < samplingRate*evict){ //pick out entries which have low hitting rate lowHit++; evictCount++; conNo = meta[1]; if(!segRecord.containsKey(conNo)){//if this segment has not been processed segRecord.put(conNo, 1);//record the container that has been resampled //locate the specific container File conToResample = new File(storageFileFolder+"/"+ conNo); Scanner inputStream = new Scanner(conToResample); //use another folder to record the new sampled de segment PrintWriter out = new PrintWriter(dirFile+"/"+ conNo); out.println("Segment No,FileName,ChunkName,ChunkSize,HashValue,reSampleTag,Hitting Rate, ContainerNo"); //start to resample, put old indexes into the temp hash record for the future use inputStream.nextLine(); while(inputStream.hasNextLine()){ String[] ary= inputStream.nextLine().split(","); out.print(ary[0]); out.print(","); out.print(ary[1]); out.print(","); out.print(ary[2]); out.print(","); out.print(ary[3]); out.print(","); out.print(ary[4]); out.print(","); long hash = Long.parseLong(ary[4].substring(30),16); if(((ary[5].substring(0,3).equals("Not"))) && check(hash)){//if the chunk was not sampled, process it // otherwise, put it into the temp hash record out.print("Re"+ary[4]); out.print(","); out.print((long)0); out.print(","); out.println(ary[7]); }else if(ary[5].substring(0,6).equals("DupNot") && check(hash)){ out.print("DupRe"+ary[4]); out.print(","); out.print((long)0); out.print(","); out.println(ary[7]); }else{ //if(!ary[5].substring(0,3).equals("Not") || !ary[5].substring(0,6).equals("DupNot")){ out.print(ary[5]); out.print(","); out.print(ary[6]); out.print(","); out.println(ary[7]); } } out.close(); } } } }
9
public static void greyWriteImage(double[][] data){ //this takes and array of doubles between 0 and 1 and generates a grey scale image from them BufferedImage image = new BufferedImage(data.length,data[0].length, BufferedImage.TYPE_INT_RGB); for (int y = 0; y < data[0].length; y++) { for (int x = 0; x < data.length; x++) { if (data[x][y]>1){ data[x][y]=1; } if (data[x][y]<0.238){ data[x][y]=0.238; } Color col=new Color((float)data[x][y],(float)data[x][y],(float)data[x][y]); image.setRGB(x, y, col.getRGB()); } } try { // retrieve image File outputfile = new File("saved.png"); outputfile.createNewFile(); ImageIO.write(image, "png", outputfile); } catch (IOException e) { //o no! Blank catches are bad throw new RuntimeException("I didn't handle this very well"); } }
5
static void selection_sort(int num[]) { int pivot,min,pos=0; for (int i=0;i<num.length-1;i++) { pivot=num[i];min=num[i+1]; for (int j=i+1;j<num.length;j++) { if(num[j]<=min) { min=num[j]; pos=j; } } if(min<pivot) { temp=pivot; num[i]=min; num[pos]=temp; } } for (int i:num) { System.out.println(i); } }
5
public void addNewNPC(NPC npc, stream str, stream updateBlock) { int id = npc.npcId; npcInListBitmap[id >> 3] |= 1 << (id&7); // set the flag npcList[npcListSize++] = npc; str.writeBits(14, id); // client doesn't seem to like id=0 int z = npc.absY-absY; if(z < 0) z += 32; str.writeBits(5, z); // y coordinate relative to thisPlayer z = npc.absX-absX; if(z < 0) z += 32; str.writeBits(5, z); // x coordinate relative to thisPlayer str.writeBits(1, 0); //something?? str.writeBits(12, npc.npcType); boolean savedUpdateRequired = npc.updateRequired; npc.updateRequired = true; npc.appendNPCUpdateBlock(updateBlock); npc.updateRequired = savedUpdateRequired; str.writeBits(1, 1); // update required }
2
public Scores copy( ) { // create new Scores object Scores temp = new Scores(); // make it identical to 'this' object for (int i=0; i<grades.length; i++) { temp.grades[i] = grades[i]; } // return the copy return temp; }
1
public Wall(int x,int y) { super(x,y); }
0
private void connect() { graph.addGraphListener( graphListener ); for( GraphItem item : items() ) { graphListener.itemAdded( graph, item ); } }
1
final static public void optionWriter(String attrib, String content) { File configf = new File(Start.sport, "config.txt"); String[] inhalt = null; boolean inside = false; if(configf.exists()) { try { inhalt = Textreader(configf); } catch (IOException e) {} for (int i=0; i<inhalt.length; i++) { if(inhalt[i].split(":")[0].equals(attrib)) { inhalt[i]=inhalt[i].split(":")[0]+":"+content; inside=true; } } } if (inside) { try { Textwriter(configf, inhalt, false); } catch (IOException e) {} } else { String[] neu = {attrib +":"+content}; try { Textwriter(configf, neu, true); } catch (IOException e) {} } }
7
public static void removeDupesHeadside(Vector someVector) { // we'll be storing census info here TreeSet censusTree = new TreeSet() ; if (censusTree == null) { return ; } // end if // grab the vector's starting size int size = someVector.size() ; // starting at the tail int position = size - 1; // local var to hold each vector element;s hashcode Integer hash = null ; // until we get all the way to the head while (position >= 0) { // grab the element's hashcode hash = new Integer(someVector.get(position).hashCode()) ; // if this element's hashcode isn't in the tree yet if (! censusTree.contains(hash)) { // add it to the tree censusTree.add(hash) ; // else this is a dupe } else { // slide more tailward elements headwards moveElementsHeadward(someVector, position + 1, size-1, 1) ; // that crushes the dupe // our size just shrunk size-- ; } // end if-else notIn-isDupe // next ! position-- ; } // end while // okay, any dupes are gone // if our size changed ... if (size < someVector.size()) { // resize someVector.setSize(size) ; // setSize cuts off from the tail end // which is correct, since we slid uniques headwards } // end if our size changed } // end method removeDupesHeadside
4
@Override public int compareTo(Interval i2) { // Start if (start > i2.start) return 1; if (start < i2.start) return -1; // End if (end > i2.end) return 1; if (end < i2.end) return -1; return 0; }
4
public static List<Car> getFreeCars() throws LoginLogicException { List<Car> freeCars = new ArrayList<Car>(); Connection connection = null; try { connection = ConnectionPool.getInstance().takeConnection(); // ������������������ �������� ������������������ ���������� �� �������������� AbstractDAO<Car> carDao = new CarDAO(connection); AbstractDAO<Order> orderDao = new OrderDAO(connection); freeCars = carDao.findAll(); List<Order> orders = orderDao.findAll(); /* �������� �������� ���������� �� �������������� �� ���� ������ ������ �� ���������������� * ������ ������������ ��������������, ���� ���������� ������������ ���������������������� * ���� ������������ ������������������ */ List<Car> nonFree = new ArrayList<Car>(); for (Order order : orders) { for (Car car : freeCars) { if ((order.getIdCar() == car.getId()) && ((!order.isFree()) || order.isCrashed())) { nonFree.add(car); } } } freeCars.removeAll(nonFree); } catch (ConnectionPoolException e) { throw new LoginLogicException("Can't take connection from connection pool.",e); } catch (DAOException e) { throw new LoginLogicException("Can't find all cars/orders.",e); } finally { ConnectionPool.getInstance().closeConnection(connection); } return freeCars; }
7
private String display() { String displayString = ""; if (data == null) { return displayString; } displayString += data.toString(); return displayString; }
1
@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((cost == null) ? 0 : cost.hashCode()); result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((partNumber == null) ? 0 : partNumber.hashCode()); result = prime * result + ((productId == null) ? 0 : productId.hashCode()); result = prime * result + ((productName == null) ? 0 : productName.hashCode()); result = prime * result + ((quantity == null) ? 0 : quantity.hashCode()); result = prime * result + ((salePrice == null) ? 0 : salePrice.hashCode()); result = prime * result + ((vatRate == null) ? 0 : vatRate.hashCode()); return result; }
8
public FoodItem orderFoodItem(String foodItemName) { return getFoodItem(foodItemName); }
0
public List<Integer> getShortedPath(Integer start, Integer stop) { dijkstra(start, stop); vertex.clear(); distance.clear(); Integer i = stop; ArrayList<Integer> path = new ArrayList<>(); while(i != start && i != null) { i = predecessors.get(i); if(i != null && !i.equals(start)){ path.add(i); } } return path; }
4
public final BufferedImage loadImage(URL imageName) { if (imageName == null) throw new NullPointerException("AssetLoader.loadImage: NULL parameter supplied."); BufferedImage image = null; try { // Attempt to load the specified image and then create a compatible // image for use with the current graphics device BufferedImage loadedImage = ImageIO.read(imageName); image = graphicsConfiguration.createCompatibleImage( loadedImage.getWidth(), loadedImage.getHeight(), loadedImage.getColorModel().getTransparency()); // Copy the loaded image to the compatible image Graphics2D g2d = image.createGraphics(); g2d.drawImage(loadedImage, 0, 0, null); g2d.dispose(); } catch (IOException e) { throw new IllegalArgumentException("AssetLoader.loadImage: " + imageName.toString() + " cannot be loaded."); } // Record the amount of loaded image data if a game statistics recorder // has been associated. It is assumed that each pixel will occupy four bytes if (gameStatisticsRecorder != null && image != null) { gameStatisticsRecorder .recordLoadedAssetSize(image.getWidth() * image.getHeight() * 4L); } return image; }
4
public boolean updateSongMetadata(MusicObject newEntry,MusicObject oldEntry) throws SQLException { if (connection == null) { connection = getConnection(); } if (updateSongStmt == null) { updateSongStmt = connection.prepareStatement("UPDATE org.MUSIC " + "SET song_name = ?, "+ "file_hash = ?, "+ "file_size = ?, "+ "album = ?, "+ "artist = ?, "+ "song_year = ?, "+ "track_on_album = ?, "+ "modified = ? "+ "WHERE file_name = ? "+ "AND folder_path = ?"); } try { log.info("Year: " + newEntry.getYear()); updateSongStmt.setString(1, newEntry.getSongName()); updateSongStmt.setString(2, newEntry.getMD5String()); updateSongStmt.setInt(3, newEntry.getSize()); updateSongStmt.setString(4, newEntry.getAlbum()); updateSongStmt.setString(5, newEntry.getArtist()); updateSongStmt.setInt(6, newEntry.getYear()); updateSongStmt.setInt(7,newEntry.getTrackOnAlbum()); updateSongStmt.setTimestamp(8, Utils.javaDateToSQL(newEntry.getLastModified())); updateSongStmt.setString(9, oldEntry.getFileName()); updateSongStmt.setString(10, oldEntry.getFolderPath()); return updateSongStmt.executeUpdate() == 1; } catch (Exception e) { log.log(Level.SEVERE, "The following error occurred when trying to add a song: " + e.getMessage(),e); closeAll(); throw new SQLException(e.getMessage()); } }
3
public String makeMove(CardGame game) { if (boardIndexTo != -1) { switch (moveType) { case FROM_DECK: return makeDeckMove(game); case FROM_BOARD: return makeBoardMove(game); case FROM_PILE: return makePileMove(game); } } return "ERROR"; }
4
@Override public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel) { final Set<MOB> h=properTargets(mob,givenTarget,auto); if(h==null) { mob.tell(L("There doesn't appear to be anyone here worth scaring.")); return false; } if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; final boolean success=proficiencyCheck(mob,0,auto); if(success) { for (final Object element : h) { final MOB target=(MOB)element; final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),L("^S<S-NAME> frighten(s) <T-NAMESELF> with <S-HIS-HER> chant.^?")); final CMMsg msg2=CMClass.getMsg(mob,target,this,verbalCastMask(mob,target,auto)|CMMsg.TYP_MIND,null); if((mob.location().okMessage(mob,msg))&&((mob.location().okMessage(mob,msg2)))) { mob.location().send(mob,msg); if(msg.value()<=0) { mob.location().send(mob,msg2); if(msg2.value()<=0) { invoker=mob; CMLib.commands().postFlee(target,""); } } } } } else return beneficialWordsFizzle(mob,null,L("<S-NAME> chant(s) in a frightening way, but the magic fades.")); // return whether it worked return success; }
8
private void initNextItem(boolean advance) { if (this.endOfPage) { nextBlock = null; return; } if (advance) { if (!iterator.next(Level.BLOCK)) { this.endOfPage = true; return; } } try { BoundingBox box = iterator.getBoundingBox(Level.BLOCK); if (box == null) { initNextItem(true); } nextBlock = new PageBlock(iterator.getBlockType(), iterator.getOrientation(), box); } catch (Exception te) { LOGGER.error("Could not initialize iterator.", te); this.nextBlock = null; } }
5
public void addRecipe() { for (int i = 0; i < 4; i++) { GameRegistry.addRecipe( new ItemStack(DCsFenceSlab.fenceslabW, 6, i), new Object[]{" X ","XXX", Character.valueOf('X'), new ItemStack(Block.planks,1,i)}); } for (int i = 0; i < 8; i++) { ItemStack itemstack = new ItemStack(Block.cobblestone,1,0); if (i == 1) itemstack = new ItemStack(Block.stone,1,0); else if (i == 2) itemstack = new ItemStack(Block.stoneBrick,1,0); else if (i == 3) itemstack = new ItemStack(Block.sandStone,1,0); else if (i == 4) itemstack = new ItemStack(Block.brick,1,0); else if (i == 5) itemstack = new ItemStack(Block.netherBrick,1,0); else if (i == 6) itemstack = new ItemStack(Block.blockNetherQuartz,1,0); else if (i == 7) itemstack = new ItemStack(Block.blockIron,1,0); else itemstack = new ItemStack(Block.cobblestone,1,0); GameRegistry.addRecipe( new ItemStack(DCsFenceSlab.fenceslabS, 6, i), new Object[]{" X ","XXX", Character.valueOf('X'), itemstack}); } }
9
public static HashMap<String, File> prepareDictionaryFiles(String path){ File dir = new File(path); if (!dir.isDirectory()){ return null; } HashMap<String, File> map = new HashMap<String, File>(); File[] files = dir.listFiles(); for (File file : files){ if (!file.isFile()){ continue; } if (file.getName().endsWith("ifo")){ map.put("ifo", file); } else if (file.getName().endsWith("idx")){ map.put("idx", file); } else if (file.getName().endsWith("dz")){ map.put("dict", file); } } return map; }
6
@BeforeClass public static void setUpClass() { }
0
public void visit_ifgt(final Instruction inst) { stackHeight -= 1; if (stackHeight < minStackHeight) { minStackHeight = stackHeight; } }
1
private void isEqualToDate(final Object param, final Object value) { if (value instanceof Date) { if (!((Date) param).equals((Date) value)) { throw new IllegalStateException("Dates are not equal."); } } else { throw new IllegalArgumentException(); } }
2
public String getShortcutToolTip() { String tip = getToolTip(); KeyStroke stroke = getKey(); if (stroke == null) return tip; int index = findDominant(tip, stroke.getKeyChar()); if (index == -1) return tip + "(" + Character.toUpperCase(stroke.getKeyChar()) + ")"; return tip.substring(0, index) + "(" + tip.substring(index, index + 1) + ")" + tip.substring(index + 1, tip.length()); }
2
void rehashPostings(final int newSize) { final int newMask = newSize-1; RawPostingList[] newHash = new RawPostingList[newSize]; for(int i=0;i<postingsHashSize;i++) { RawPostingList p0 = postingsHash[i]; if (p0 != null) { int code; if (perThread.primary) { final int start = p0.textStart & DocumentsWriter.CHAR_BLOCK_MASK; final char[] text = charPool.buffers[p0.textStart >> DocumentsWriter.CHAR_BLOCK_SHIFT]; int pos = start; while(text[pos] != 0xffff) pos++; code = 0; while (pos > start) code = (code*31) + text[--pos]; } else code = p0.textStart; int hashPos = code & newMask; assert hashPos >= 0; if (newHash[hashPos] != null) { final int inc = ((code>>8)+code)|1; do { code += inc; hashPos = code & newMask; } while (newHash[hashPos] != null); } newHash[hashPos] = p0; } } postingsHashMask = newMask; postingsHash = newHash; postingsHashSize = newSize; postingsHashHalfSize = newSize >> 1; }
7
private Integer calVer(String s) throws NumberFormatException { if (s.contains(".")) { final StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.length(); i++) { final Character c = s.charAt(i); if (Character.isLetterOrDigit(c)) { sb.append(c); } } return Integer.parseInt(sb.toString()); } return Integer.parseInt(s); }
3
public void setCode(long value) { this._code = value; }
0
public void creaAutomataCerradura(int tipoCerradura) { try { if (tipoCerradura == 0) { System.out.println("Generando automata para cerradura epsilon..."); } else { System.out.println("Generando automata para cerradura positiva..."); } int[] inicio_finTope = inicio_fin.pop(); //System.out.println("-Tomado de pila inicio_fin: " + inicio_finTope[0] + "," +inicio_finTope[1]); //----- FIN+1 --> INICIO String[] automataHijo = new String[3]; automataHijo[0] = (inicio_finTope[1] + 1) + ""; automataHijo[1] = "@"; automataHijo[2] = inicio_finTope[0] + ""; agregarAPilaAFN(automataHijo); if (tipoCerradura == 0) { //----- FIN+1 --> FIN+2 automataHijo = new String[3]; automataHijo[0] = (inicio_finTope[1] + 1) + ""; automataHijo[1] = "@"; automataHijo[2] = (inicio_finTope[1] + 2) + ""; agregarAPilaAFN(automataHijo); } //----- FIN --> FIN+2 automataHijo = new String[3]; automataHijo[0] = (inicio_finTope[1]) + ""; automataHijo[1] = "@"; automataHijo[2] = (inicio_finTope[1] + 2) + ""; agregarAPilaAFN(automataHijo); //----- FIN --> INICIO automataHijo = new String[3]; automataHijo[0] = (inicio_finTope[1]) + ""; automataHijo[1] = "@"; automataHijo[2] = (inicio_finTope[0]) + ""; System.out.println("Nuevo estado final: " + (ultimoEstadoFinal + 1)); System.out.println("Nuevo estado final: " + (ultimoEstadoFinal + 2)); setUltimoEstadoInicial(ultimoEstadoFinal + 1); setUltimoEstadoFinal(ultimoEstadoFinal + 2); inicio_finTope[0] = this.ultimoEstadoInicial; inicio_finTope[1] = this.ultimoEstadoFinal; setConjuntoDeEstados(inicio_finTope[0] + ""); setConjuntoDeEstados(inicio_finTope[1] + ""); agregarAPilaAFN(automataHijo); agregarAPilaInicio_Fin(inicio_finTope); imprimirPilaAutomata(); imprimirPilaInicioFin(); } catch (EmptyStackException ese) { ese.getStackTrace(); System.out.println("La pila est\u00E1 vac\u00CDa"); setBanderaError(); } }
3
protected App() { if (Platform.isMacintosh()) { Application app = Application.getApplication(); app.setAboutHandler(AboutCommand.INSTANCE); app.setPreferencesHandler(PreferencesCommand.INSTANCE); app.setOpenFileHandler(OpenCommand.INSTANCE); app.setPrintFileHandler(PrintCommand.INSTANCE); app.setQuitHandler(QuitCommand.INSTANCE); app.setQuitStrategy(QuitStrategy.SYSTEM_EXIT_0); app.disableSuddenTermination(); } }
1
public ArrayList<Integer> spiralOrder(final List<List<Integer>> a) { ArrayList<Integer> result = new ArrayList<Integer>(); boolean left = true; boolean right = false; boolean top = false; boolean down = false; int lci = 0; int rci = a.get(0).size() -1; int tri = 0; int bri = a.size() -1; int N = a.size() * a.get(0).size(); int scanCount = 0; while(scanCount < N) { if(left == true) { List<Integer> row = a.get(tri); for(int i=lci; i <= rci;i++) { Integer val = row.get(i); result.add(val); scanCount++; } left = false; down = true; tri++; } else if(down == true) { for(int i = tri; i <= bri; i++) { List<Integer> row = a.get(i); Integer val = row.get(rci); result.add(val); scanCount++; } right = true; down = false; rci--; } else if(right == true) { List<Integer> row = a.get(bri); for(int i=rci; i >= lci; i--) { Integer val = row.get(i); result.add(val); scanCount++; } right = false; top = true; bri--; } else if(top == true) { for(int i= bri; i >= tri; i--) { List<Integer> row = a.get(i); Integer val = row.get(lci); result.add(val); scanCount++; } top = false; left = true; lci++; } } return result; }
9
public void append(String fileName,String message){ try { BufferedWriter writer = new BufferedWriter(new FileWriter(fileName,true)); writer.write(message); writer.close(); }catch (java.io.IOException e) { this.plugin.logMessage("Unable to write to "+fileName+": "+e.getMessage()); } }
1
public static void main(String[] args) { System.out.println(Runtime.getRuntime().availableProcessors()); }
0
public JPanel getMiscMenu() { if (!isInitialized()) { IllegalStateException e = new IllegalStateException("Call init first!"); throw e; } return this.misc; }
1
public boolean femaleAgree() { if ((passion <= 80) && (this.previousAction != 3)) return true; return false; }
2
public void addFishes(Fishes fishes) { Iterator<Fish> ite = fishes.Iterator(); while (ite.hasNext()) { Fish fish = ite.next(); for (int i = 0; i < fishContainers.size(); i++) { if (fishContainers.get(i).getName().equals(fish.getName())) { if (fishContainers.get(i).getMin() <= fish.getLength() && fishContainers.get(i).getMax() >= fish .getLength()) { fishContainers.get(i).addFish(fish); break; } } } } }
5
protected boolean in_grouping_b(char [] s, int min, int max) { if (cursor <= limit_backward) return false; char ch = current.charAt(cursor - 1); if (ch > max || ch < min) return false; ch -= min; if ((s[ch >> 3] & (0X1 << (ch & 0X7))) == 0) return false; cursor--; return true; }
4
private static Controller getController(final String uri, final String method) throws GameServerException { if (uri.matches(LOGIN_SUFIX_PATTERN) && method.equals(GET_METHOD)) { return ApplicationContext.getLoginController(); } else if (uri.matches(POST_SCORE_PATTERN) && method.equals(POST_METHOD)) { return ApplicationContext.getPostScoreController(); } else if (uri.matches(HIGHSCORE_SUFIX_PATTERN) && method.equals(GET_METHOD)) { return ApplicationContext.getHighScoreController(); } throw new GameServerException(); }
6
public void setzPhase(int startEinheiten) { while(startEinheiten > 0) { spieler1.einheitenSetzen(1, laenderGraph); wechsleSpieler(aktuellerSpieler); spieler2.einheitenSetzen(1, laenderGraph); wechsleSpieler(aktuellerSpieler); startEinheiten--; } }
1
public static long removeAddress(Address address, long sessionID) throws SessionException { if (sessionID <= NO_SESSION_ID) { throw new SessionException("A valid session ID is required to remove an address", SessionException.SESSION_ID_REQUIRED); } Contact contact = (Contact) editContacts.get(new Long(sessionID)); if (contact == null) { throw new SessionException("You must select a contact before removing an address", SessionException.CONTACT_SELECT_REQUIRED); } if (addresses.indexOf(address) == -1) { throw new SessionException("There is no record of this address", SessionException.ADDRESS_DOES_NOT_EXIST); } contact.removeAddress(address); return sessionID; }
3
private Iterator<Entry<String, String>> getTemplateLocations() { final Log log = getLog(); List<Resource> r = this.resources; //If no resources specified if (r == null) { final Resource resource = new Resource(); resource.source = new FileSet(); resource.source.setDirectory(this.sassSourceDirectory.toString()); if (this.includes != null) { resource.source.setIncludes(Arrays.asList(this.includes)); } if (this.excludes != null) { resource.source.setExcludes(Arrays.asList(this.excludes)); } resource.relativeOutputDirectory = this.relativeOutputDirectory; resource.destination = this.destination; r = ImmutableList.of(resource); } List<Entry<String, String>> locations = new ArrayList<Entry<String, String>>(); for (final Resource source : r) { for (final Entry<String, String> entry : source.getDirectoriesAndDestinations().entrySet()) { log.info("Queueing SASS Template for compile: " + entry.getKey() + " => " + entry.getValue()); locations.add(entry); } } return locations.iterator(); }
5
public ContextFreeGrammar convertToContextFreeGrammar(Automaton automaton) { /** check if automaton is pda. */ if (!(automaton instanceof PushdownAutomaton)) throw new IllegalArgumentException( "automaton must be PushdownAutomaton"); if (!isInCorrectFormForConversion(automaton)) throw new IllegalArgumentException( "automaton not in correct form for conversion to CFG"); initializeConverter(); ArrayList list = new ArrayList(); ContextFreeGrammar grammar = new ContextFreeGrammar(); Transition[] transitions = automaton.getTransitions(); for (int k = 0; k < transitions.length; k++) { list.addAll(createProductionsForTransition(transitions[k], automaton)); } Iterator it = list.iterator(); while (it.hasNext()) { Production p = (Production) it.next(); grammar.addProduction(getSimplifiedProduction(p)); } return grammar; }
4
private void submit(Schedule schedule, Teacher teacher) { String error = ""; if(schedule == null) { error += " - schedule \n"; } if(teacher.getId() <= 0) { error += " - teacher \n"; } if(schedule != null && teacher.getId() > 0){ //Component c = tabbedPane.getSelectedComponent(); this.group_schedule.setSchedule(schedule); this.group_schedule.setTeacher(teacher); ScheduleSelectDialog.this.dispose(); listener.returnGroup_schedule(this.group_schedule); } else { JOptionPane.showMessageDialog(this, "Please select: \n" + error); } }
4
public FullPalletTest() { ArrayList<CSIColor> list = new ArrayList<CSIColor>(); for (int i = 0; i < CSIColor.FULL_PALLET.length; i++) { list.add(CSIColor.FULL_PALLET[i]); } Collections.sort(list); try { mainInterface = new WSwingConsoleInterface("CSIColor Test"); } catch (ExceptionInInitializerError eiie) { System.out.println("Fatal Error Initializing Swing Console Box"); eiie.printStackTrace(); System.exit(-1); } int x = 0, times = 0; CSIColor tempColor = CSIColor.WHITE, backColor = CSIColor.BLACK; for (int k = 0; k < mainInterface.getYdim(); k++) { for (int i = 0; i < mainInterface.getXdim(); i++) { if (!(x < list.size())) { x = 0; times++; } tempColor = list.get(x); x++; switch (times) { case 0: backColor = CSIColor.BLACK; break; case 1: backColor = CSIColor.GRAY; break; case 2: backColor = CSIColor.WHITE; break; case 3: backColor = CSIColor.BLACK; times = 0; } mainInterface.print(i, k, 'Q', new CSIColor(tempColor), new CSIColor(backColor)); } } }
9
public void removeLoginListener(LoginListener listener){ loginListeners.remove(listener); }
0
public void initializeServerWithPersistDataInServer() throws IOException, CubeXmlFileNotExistsException, DocumentException, CubeAlreadyExistsException, CorrespondingDimensionNotExistsException, SchemaAlreadyExistsException, CorrespondingSchemaNotExistsException, CubeElementsNotExistsException { SchemaClientInterface schemaClient = SchemaClient.getSchemaClient(); // read Schemas PersistSchemaReader persistSchemaReader = new PersistSchemaReader(); SortedSet<Schema> schemas = persistSchemaReader.read(); // read cubes PersistCubeReader persistCubeReader = new PersistCubeReader(); SortedSet<Cube> cubes = persistCubeReader.read(); // check whether cubes, schemas and cubeElements consistent String schemaName; String cubeIdentifier; long numberOfPages; for (Cube cube : cubes) { schemaName = cube.getSchemaName(); // if not find, CorrespondingSchemaNotExistsException will be thrown Schema schema = findCorrespondingSchema(schemaName, schemas); cubeIdentifier = cube.getIdentifier(); numberOfPages = PageHelper.getNumberOfPages(schema); if (!isCubeElementsExists(cubeIdentifier, numberOfPages)) { throw new CubeElementsNotExistsException(); } } // add schemas for (Schema schema : schemas) { schemaClient.addSchema(schema); } // add cubes for (Cube cube : cubes) { schemaClient.addCube(cube); } }
4
private Boolean checkType(String value, String dataType){ Boolean ret = false; if( "#int".equals(dataType)){ try{ Integer.parseInt(value); return true; }catch(NumberFormatException e) { return false; } } else if("#char".equals(dataType)){ value = value.substring(1); ret = (value.length()>1)? false: true; } else if("#boolean".equals(dataType)){ ret = ("false".equals(value)|| "true".equals(value))? true: false; } return ret; }
7
public static void main(String[] args) { for (int i = 0; i < 10; i++) { Tourist person = new Tourist(); try { person.takeTour(); // if an exception is thrown from previous line, this next // instruction is not executed System.out.printf("Tourist %d say: This is cool%n", i + 1); } catch (TooHotException hx) { System.out.printf("Tourist %d say: %s%n", i + 1, hx.getMessage()); continue; } catch (TooColdException hx) { System.out.printf("Tourist %d say: %s%n", i + 1, hx.getMessage()); continue; } finally { System.out.println(); } } }
3
public static By parse(String elementLocator) throws InvalidSeleneseCommandArgumentException { String matched; for(ElementLocator locator : ElementLocator.values()) { if((matched = locator.find(elementLocator)) != null) { switch(locator) { case ID : return By.id(matched); case NAME : return By.name(matched); case XPATH: return By.xpath(matched); case LINK : return By.linkText(matched); case CSS : return By.cssSelector(matched); } } } throw new InvalidSeleneseCommandArgumentException(elementLocator); }
7
/* */ public void run() /* */ { /* */ while (true) /* */ { /* */ try { /* 157 */ Thread.sleep(17L); /* */ } catch (Exception e) { /* 159 */ e.printStackTrace(); /* */ } /* */ /* 162 */ for (int i = 0; i < landingboats.size(); i++) { /* 163 */ LandingBoat l = (LandingBoat)landingboats.get(i); /* 164 */ l.update(); /* */ } /* 166 */ for (int i = 0; i < units.size(); i++) { /* 167 */ Unit u = (Unit)units.get(i); /* 168 */ u.update(17); /* */ } /* 170 */ repaint(); /* */ } /* */ }
4
private Grammar trim(Production[] prods) { myVariableMap=new HashMap <String, String>(); char ch='A'; for (int i=0; i<prods.length; i++) { String lhs=prods[i].getLHS(); if (ch=='S' || ch=='T') { ch++; } int aa=lhs.indexOf("V("); while (aa>-1) { // System.out.println("in 1st "+lhs+"===> "); int bb=lhs.indexOf(")"); String var=""; if ((aa+bb+1) > lhs.length()) { var=lhs.substring(aa, aa+bb); lhs=lhs.substring(0, aa)+ch; } else { var=lhs.substring(aa, aa+bb+1); lhs=lhs.substring(0, aa)+ch+lhs.substring(aa+bb); } // System.out.println(var+ " and new lhs is = "+lhs); aa=lhs.indexOf("V("); myVariableMap.put(""+ch, var); // System.out.println(var+" converted to : "+ch); // lhs.replaceAll("V"+aa[j], "A"); for (int k=0; k<prods.length; k++) { String inner_lhs=prods[k].getLHS(); String inner_rhs=prods[k].getRHS(); int a=inner_lhs.indexOf(var); if (a>-1) { // System.out.println("in inner lhs "+inner_lhs+" ===> "); inner_lhs=inner_lhs.substring(0, a)+""+ch+inner_lhs.substring(a+var.length()); // System.out.println(inner_lhs); } a=inner_rhs.indexOf(var); if (a>-1) { // System.out.println("in inner rhs "+inner_rhs+" ===> "); inner_rhs=inner_rhs.substring(0, a)+""+ch+inner_rhs.substring(a+var.length()); // System.out.println(inner_rhs); } prods[k]=new Production(inner_lhs, inner_rhs); } ch=(char) (ch+1); // System.out.println(lhs); } } Grammar g=new UnrestrictedGrammar(); g.addProductions(prods); return g; }
8
private void handleEvents(int keyCode) { switch (applicationState.getState()) { case ApplicationState.MAIN_MENU: handleMainMenu(keyCode); break; case ApplicationState.HELP: case ApplicationState.ABOUT: handleHelpAndAbout(keyCode); break; case ApplicationState.OPTIONS: handleOptions(keyCode); break; case ApplicationState.EXIT: handleExit(keyCode); break; case ApplicationState.METRONOME_STARTED: case ApplicationState.METRONOME_STOPPED: handleMetronome(keyCode); break; } }
7
private void createNetwork(int inputs,int outputs){ if(currentSpecies==null){ if(net==null){ System.out.println("Neural Network created in net"); net=new SpeciationNeuralNetwork(history,inputs,outputs); if(net2==null) currentNetwork=net; }else if(net2==null){ System.out.println("Neural Network created in net2"); net2=new SpeciationNeuralNetwork(history,inputs,outputs); if(net==null) currentNetwork=net2; }else if(net==currentNetwork){ System.out.println("Neural Network created in net2"); net2=null; net2=new SpeciationNeuralNetwork(history,inputs,outputs); }else{ // net2==currentNetwork System.out.println("Neural Network created in net"); net=null; net=new SpeciationNeuralNetwork(history,inputs,outputs); } }else{ System.out.println("Neural Network created in the current species"); currentSpecies.getIndividuals().add(new SpeciationNeuralNetwork(history,inputs,outputs)); } }
6
public synchronized void close() { if (isClosed) { return; } isClosed = true; if (cycLeaseManager != null) { cycLeaseManager.interrupt(); } if (cycConnection != null) { cycConnection.close(); } if (areAPIRequestsLoggedToFile) { try { apiRequestLog.close(); } catch (IOException e) { System.err.println("error when closing apiRequestLog: " + e.getMessage()); } } cycAccessInstances.remove(Thread.currentThread()); // make sure it's not every used again for setting as the 'current' CycAccess. for (Map.Entry<String, CycAccess> entry : currentCycAccesses.entrySet()) { if (entry.getValue().equals(this)) { currentCycAccesses.remove(entry.getKey()); } } /*if (sharedCycAccessInstance == null || sharedCycAccessInstance.equals(this)) { final Iterator iter = cycAccessInstances.values().iterator(); if (iter.hasNext()) sharedCycAccessInstance = (CycAccess) iter.next(); else sharedCycAccessInstance = null; }*/ }
7
@SuppressWarnings("unchecked") void readGaussianBasis() throws Exception { Vector sdata = new Vector(); Vector gdata = new Vector(); atomCount = 0; gaussianCount = 0; int nGaussians = 0; shellCount = 0; String thisShell = "0"; String[] tokens; discardLinesUntilContains("SHELL TYPE PRIMITIVE"); readLine(); Hashtable slater = null; while (readLine() != null && line.indexOf("TOTAL") < 0) { tokens = getTokens(line); switch (tokens.length) { case 1: atomCount++; case 0: break; default: if (!tokens[0].equals(thisShell)) { if (slater != null) { slater.put("nGaussians", new Integer(nGaussians)); sdata.add(slater); } thisShell = tokens[0]; shellCount++; slater = new Hashtable(); slater.put("atomIndex", new Integer(atomCount - 1)); slater.put("basisType", tokens[1]); slater.put("gaussianPtr", new Integer(gaussianCount)); // or parseInt(tokens[2]) - 1 nGaussians = 0; } ++nGaussians; ++gaussianCount; gdata.add(tokens); } } if (slater != null) { slater.put("nGaussians", new Integer(nGaussians)); sdata.add(slater); } float[][] garray = new float[gaussianCount][]; for (int i = 0; i < gaussianCount; i++) { tokens = (String[]) gdata.get(i); garray[i] = new float[tokens.length - 3]; for (int j = 3; j < tokens.length; j++) garray[i][j - 3] = parseFloat(tokens[j]); } moData.put("shells", sdata); moData.put("gaussians", garray); logger.log(shellCount + " slater shells read"); logger.log(gaussianCount + " gaussian primitives read"); }
9
protected void onMouseClick(int var1, int var2, int var3) { if(var3 == 0) { for(var3 = 0; var3 < this.buttons.size(); ++var3) { Button var4; Button var7; if((var7 = var4 = (Button)this.buttons.get(var3)).active && var1 >= var7.x && var2 >= var7.y && var1 < var7.x + var7.width && var2 < var7.y + var7.height) { this.onButtonClick(var4); } } } }
7
@Override public void setName(String name) { this.name = name; }
0
public boolean replaceSubBlock(StructuredBlock oldBlock, StructuredBlock newBlock) { if (bodyBlock == oldBlock) bodyBlock = newBlock; else return false; return true; }
1
public void run() { try { boolean eos=false; byte[] buffer=new byte[8192]; while(!eos) { OggPage op=OggPage.create(source); synchronized (drainLock) { pageCache.add(op); } if(!op.isBos()) { bosDone=true; } if(op.isEos()) { eos=true; } LogicalOggStreamImpl los=(LogicalOggStreamImpl)getLogicalStream(op.getStreamSerialNumber()); if(los==null) { los=new LogicalOggStreamImpl(UncachedUrlStream.this, op.getStreamSerialNumber()); logicalStreams.put(new Integer(op.getStreamSerialNumber()), los); los.checkFormat(op); } //los.addPageNumberMapping(pageNumber); //los.addGranulePosition(op.getAbsoluteGranulePosition()); pageNumber++; while(pageCache.size()>PAGECACHE_SIZE) { try { Thread.sleep(200); } catch (InterruptedException ex) { } } } } catch(EndOfOggStreamException e) { // ok } catch(IOException e) { e.printStackTrace(); } }
8
public static String longToPlayerName(long l) { if (l <= 0L || l >= 0x5b5b57f8a98a5dd1L) { return null; } if (l % 37L == 0L) { return null; } int i = 0; char ac[] = new char[12]; while (l != 0L) { long l1 = l; l /= 37L; ac[11 - i++] = VALID_CHARS[(int)(l1 - l * 37L)]; } return new String(ac, 12 - i, i); }
4
public void backup(int amount) { inBuf += amount; if ((bufpos -= amount) < 0) bufpos += bufsize; }
1
public DVConstraints dvConstraints() throws ConstraintException { final DVConstraints result = DataFactory.getInstance().createDVConstraints(); final Term term = getValue(); if (term.isVariable()) return result; final Functor functor = (Functor) term; if (functor.definitionDepth() == 0) { for (final Expression childExp: getChildren()) result.add(childExp.dvConstraints()); return result; } final jhilbert.expressions.ExpressionFactory expressionFactory = ExpressionFactory.getInstance(); final Definition definition = (Definition) functor; final List<Variable> arguments = new ArrayList(definition.getArguments()); final List<Expression> children = getChildren(); final Expression unfoldedExpression = definition.unfold(children); result.add(unfoldedExpression.dvConstraints()); assert (arguments.size() == children.size()): "args/children count mismatch"; final int size = arguments.size(); final Map<Variable, Expression> varMap = new HashMap(); for (int i = 0; i != size; ++i) { varMap.put(arguments.get(i), children.get(i)); } for (final Variable[] dv: definition.getDVConstraints()) { assert (dv.length == 2): "Invalid DV length"; Expression exp0 = varMap.get(dv[0]); Expression exp1 = varMap.get(dv[1]); if (exp0 == null) exp0 = expressionFactory.createExpression(dv[0]); if (exp1 == null) exp1 = expressionFactory.createExpression(dv[1]); result.addProduct(exp0.variables(), exp1.variables()); } return result; }
7
public static void main(String[] args) { int sum = 0; for (int i = 1; i <= 1000; i++) { if (i % 3 == 0 || i % 5 == 0) { sum += i; } } System.out.println(sum); }
3
private void create() { shell = new Shell(SWT.APPLICATION_MODAL | SWT.CLOSE ); shell.setText("Project File Restore/Replace"); shell.setMinimumSize(450, 250); GridLayout layout = new GridLayout(1,false); shell.setLayout(layout); layout.horizontalSpacing = 5; layout.verticalSpacing = 5; layout.makeColumnsEqualWidth = true; // Groups Group restoreGroup = new Group(shell, SWT.NONE); restoreGroup.setText("Restore/Replace"); restoreGroup.setLayout(new GridLayout(2,false)); Group statusGroup = new Group(shell, SWT.NONE); statusGroup.setText("Status"); statusGroup.setLayout(new GridLayout(1,false)); // Status box final ProgressBar progress = new ProgressBar(statusGroup, SWT.NONE); progress.setMaximum(100); progress.setMinimum(0); progress.setSelection(0); final Text status = new Text( statusGroup, SWT.MULTI | SWT.READ_ONLY | SWT.V_SCROLL ); // Restore box final Text file = new Text(restoreGroup, SWT.SINGLE | SWT.BORDER ); Button browse = new Button(restoreGroup, SWT.PUSH); browse.setText("Browse..."); final Combo symCombo = new Combo(restoreGroup, SWT.DROP_DOWN); for( int sym: Config.getSyms() ) { symCombo.add("Sym " + sym); } Button doit = new Button(restoreGroup, SWT.PUSH ); doit.setText("Replace"); browse.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { org.eclipse.swt.widgets.FileDialog f = new org.eclipse.swt.widgets.FileDialog(shell, SWT.OPEN); String fn = f.open(); if( fn != null ) file.setText(fn); } }); doit.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { // Oh my god, error checking like this sucks. I am tempted to make an // "easy error dialog" static method... Imagine... // ErrorBox.open("Error: no file specified", "You must specify a file to continue"); // that would be so much nicer than this crappy 7 line method of doing it. if( file.getText() == null || !(new File(file.getText())).exists() ) { MessageBox error = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR); error.setText("File Error"); error.setMessage("You must specify a file that exists."); error.open(); return; } if( symCombo.getSelectionIndex() == -1 ) { MessageBox error = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR); error.setText("Select a sym"); error.setMessage("You must select a sym"); error.open(); return; } int sym = Integer.parseInt( symCombo.getItem(symCombo.getSelectionIndex()).substring(4) ); if( RepDevMain.SYMITAR_SESSIONS.get(sym).isConnected() ) { MessageBox error = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR ); error.setText("Not logged out"); error.setMessage("You must log out of the sym that you want to restore your project file in"); error.open(); return; } progress.setSelection(10); status.setText(status.getText() + "Logging in to sym " + sym + "\r\n" ); int err = SymLoginShell.symLogin(shell.getDisplay(), shell, sym); if( err != -1 ) { progress.setSelection(25); SymitarSession session = RepDevMain.SYMITAR_SESSIONS.get(sym); SymitarFile pf = new SymitarFile(sym,"repdev." + session.getUserNum(true) + "projects", FileType.REPGEN); status.setText(status.getText() + "Replacing Project file for " + session.getUserNum(true) + " on sym " + sym + "...\r\n"); try { progress.setSelection(40); File f = new File(file.getText()); FileReader project = new FileReader(f); char[] data = new char[(int)f.length()]; project.read(data); progress.setSelection(50); SessionError se = session.saveFile(pf, new String(data)); progress.setSelection(80); status.setText(status.getText() + "Finished, errors: " + se.toString() + "\r\n" ); } catch (FileNotFoundException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } session.disconnect(); progress.setSelection(100); } } }); // restoreGroup's layout data GridData data = new GridData(SWT.FILL, SWT.TOP, true, false); restoreGroup.setLayoutData(data); file.setLayoutData(new GridData(SWT.FILL,SWT.TOP,true,false)); symCombo.setLayoutData(new GridData(SWT.FILL,SWT.TOP,true,false)); browse.setLayoutData(new GridData(SWT.FILL,SWT.TOP,true,false)); doit.setLayoutData(new GridData(SWT.FILL,SWT.TOP,true,false)); // inside of statusGroup... data = new GridData(SWT.FILL, SWT.TOP, true, false ); progress.setLayoutData(data); data = new GridData(SWT.FILL, SWT.FILL, true, true); status.setLayoutData(data); // For the status group's layout stuff... data = new GridData(SWT.FILL, SWT.FILL, true, true); statusGroup.setLayoutData(data); restoreGroup.pack(); statusGroup.pack(); shell.pack(); shell.open(); }
9
public void showTable() { waitlb1.setVisible(true); if (!l.isEmpty()) { if (r2.isSelected()) { if (tmpHead == null) { tmpHead = l.get(0); l.remove(0); } else if (l.get(0).equals(tmpHead)) { l.remove(0); } } else { if (tmpHead != null && !l.get(0).equals(tmpHead)) { l.add(0, tmpHead); } } content = new String[l.size()][l.get(0).split(";").length]; for (int i = 0; i < l.size(); i++) { content[i] = l.get(i).split(";"); } dtm.setDataVector(content, head); finishBtn.setEnabled(true); } else { finishBtn.setEnabled(false); } waitlb1.setVisible(false); }
7
public static int highestNumberPerimeter(int upperBound) { int perimeter = 1, a = 1, b = 1, c = 1, max = 0; int[] numberOfCombinations = new int[upperBound]; // Initialize the array to all zeros for (int i = 0; i < upperBound; i++) { numberOfCombinations[i] = 0; } //Find all the right triangles to upperBound for (c = 1; c < upperBound / 2; c++) { for (b = 1; b < c; b++) { for (a = 1; a < b || a == b; a++) { if (isRightTriangle(a, b, c) && (a + b + c) < upperBound) { numberOfCombinations[a + b + c - 1] += 1; } } } } for (int i = 0; i < numberOfCombinations.length; i++) { if (numberOfCombinations[i] > numberOfCombinations[max]) { max = i; } } return max + 1; // keep a return number for the IDE }
9
public static int encontrarMultiplosDe7(int[] v, int a, int b){ if (a == b) { if (v[a] % 7 == 0) return 1; else return 0; } else { if (a < b) { while (a < b) { if (v[a] % 7 == 0) return 1 + encontrarMultiplosDe7(v, a + 1, b); else return encontrarMultiplosDe7(v, a + 1, b); } } else { while (b < a) { if (v[b] % 7 == 0) return 1 + encontrarMultiplosDe7(v, a, b + 1); else return encontrarMultiplosDe7(v, a, b + 1); } } } return 0; }
7
@Override public void run() { requestFocus(); Image image = new BufferedImage(800, 600, BufferedImage.TYPE_INT_ARGB); while(isRunning) { Graphics g = image.getGraphics(); g.drawImage(Images.background,0,0,null); level.render(g); g.dispose(); level.tick(input); try { g = getGraphics(); g.drawImage(image,0,0,WINDOWX,WINDOWY,0,0,400,300,null); g.dispose(); } catch (Throwable e) { e.printStackTrace(); } } }
2
boolean releaseSystemKey(int keyValue){ try{ Robot r = new Robot(); r.keyRelease(keyValue); if( isShift==true ) shiftOff(); if( isCtrl==true ) ctrlOff(); return true; }catch(Exception e){ System.out.println(e); return false; } }
3
public void testAvailabe(int H, int V, int A) { // H&V number want be bls of // indH &indV A = index if ((this.indexH + H) >= 8 || (this.indexV + V) >= 8 || (this.indexV + V) < 0 || (this.indexH + H) < 0) { this.availableCells[A] = null; } else if (myBoard.bordaCell[this.indexH + H][this.indexV + V].cellPiece == null) { // if // cell // null if (myBoard.bordaCell[this.indexH + H][this.indexV + V].getIndV() != this.indexV) {// this // problem this.availableCells[A] = null; } else { this.availableCells[A] = myBoard.bordaCell[this.indexH + H][this.indexV + V]; } } else if (myBoard.bordaCell[this.indexH + H][this.indexV + V].cellPiece.team == this.team) { this.availableCells[A] = null; } else if (myBoard.bordaCell[this.indexH + H][this.indexV + V] .getIndV() == this.indexV) { this.availableCells[A] = null; } else { this.availableCells[A] = myBoard.bordaCell[this.indexH + H][this.indexV + V]; } return; }
8
public boolean isXCollision(int x) { Point midpoint = getMidPoint(x, y, BOAT_WIDTH, BOAT_HEIGHT, rotation); int centreX = (int) midpoint.getX(); int centreY = (int) midpoint.getY(); //Color c = new Color(map.grass.getRGB(centreX, centreY)); if (centreX > 150 && centreX < 1050 && centreY > 0 && centreY < map.grass.getHeight()) { Color c = new Color(map.grass.getRGB(centreX-150, centreY)); //System.out.println("(" + (centreX-150) + ", " + centreY +")" + c.getGreen()); if (c.getGreen() == 128) { return true; } } if(midpoint.getX() < 150.0) return true; if(midpoint.getX() > gameWidth - 150.0) return true; return false; }
7
private Object getValueOfProperty(Object o, Method method, Field field) { // read! Object value = null; try { method.setAccessible(true); value = method.invoke(o, new Object[] {}); } catch (IllegalArgumentException e) { } catch (IllegalAccessException e) { } catch (InvocationTargetException e) { } // read from property directly if the value // is still null if (value == null) { if (field != null) { try { field.setAccessible(true); value = field.get(o); } catch (IllegalArgumentException e) { } catch (IllegalAccessException e) { } } } return value; }
7
public String getTypeString(Type type) { if (type instanceof ArrayType) return getTypeString(((ArrayType) type).getElementType()) + "[]"; else if (type instanceof ClassInterfacesType) { ClassInfo clazz = ((ClassInterfacesType) type).getClassInfo(); return getClassString(clazz, Scope.CLASSNAME); } else if (type instanceof NullType) return "Object"; else return type.toString(); }
3
public FenetreBuffersTailles(){ int jjj=0; System.out.println("tableauxxx"+ tableauxx.size()); //tableauxx.clear(); System.out.println("tableauxxxdddd"+ FenetreBuffersNumeros.getTableauTailles().size()); srids.clear(); System.out.println("srids"+ FenetreBuffersNumeros.getSrids().size()); System.out.println("srids"+ srids.size()); nombreClasses.clear(); nomCouches.clear(); valeurs.clear(); System.out.println("nomCouches"+ nomCouches.size()); System.out.println("nombreClasses"+ nombreClasses.size()); FenetreBuffersTailles.tableauxx=FenetreBuffersNumeros.getTableauTailles(); System.out.println("tableaux"+ tableauxx.size()); for(int fg=0;fg<FenetreBuffersNumeros.getTableauTailles().size();fg++){ String test34[][]=FenetreBuffersNumeros.getTableauTailles().get(fg); String taillePixels=test34[fg][1]; nombreClasses.add(taillePixels); String nomCouche=test34[fg][0].toString(); nomCouches.add(nomCouche); } srids=FenetreBuffersNumeros.getSrids(); System.out.println("nombreClasses"+ nombreClasses.size()); for(int fg=0;fg<srids.size();fg++){ System.out.println("srids"+ srids.get(fg)); } System.out.println("buffer"+ nombreClasses.get(0)); System.out.println("buffer"+ nomCouches.get(0)); System.out.println("reclassification2"); for(int i=0;i<nombreClasses.size();i++){ valeurs.add(Double.parseDouble(nombreClasses.get(i))); } String max=""; double maxi; double[] numbers = new double[nombreClasses.size()]; // this.connexion=connexion; if(FenetreBuffersTailles.nomShape1.size()==0){ FenetreBuffersTailles.nomShape1=Rreclassification.getNomCouches(); maximValues=Rreclassification.getMaximCouches(); } this.setLocationRelativeTo(null); //this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); //this.setDefaultCloseOperation(this.nomShape1.remove(0)); this.setTitle("JTable5678"); this.setSize(500, 240); // final DefaultTableModel model = new DefaultTableModel(); // final JTable tableau = new JTable(model); // tableau.setColumnSelectionAllowed (true); // tableau.setRowSelectionAllowed (false); TableColumn ColumnName = new TableColumn(); ColumnName.setMinWidth(200); model.addColumn(ColumnName); TableColumn ColumnName2 = new TableColumn(); ColumnName2.setMinWidth(200); model.addColumn(ColumnName2); tableau.getColumnModel().getColumn(0).setHeaderValue(new String("Nom")); tableau.getColumnModel().getColumn(1).setHeaderValue(new String("Valeur")); tableau.getSelectionModel().addListSelectionListener(new ListSelectionListener() { public synchronized void valueChanged(ListSelectionEvent abc) { // TODO Auto-generated method stub setSel(tableau.getSelectedRow()); System.out.println("sel"+getSel()); } }); for (int efg=0;efg<nomCouches.size();efg++){ //// a revoir, probleme nomcouches System.out.println("efg"+nomCouches.get(efg)); } for(jjj=0;jjj<valeurs.size();jjj++){ System.out.println("jjj"+valeurs.get(jjj)); } for (int efg=0;efg<nomCouches.size();efg++){ //// a revoir, probleme nomcouches // model.addRow(new Object []{nomCouches.get(efg)}); for(jjj=0;jjj<valeurs.get(efg);jjj++){ model.addRow(new Object [] {nomCouches.get(efg),""}); srids1.add(srids.get(efg)); } } for(int fg=0;fg<srids1.size();fg++){ System.out.println("srids1"+ srids1.get(fg)); } //this.model.removeRow(1); JPanel pan = new JPanel(); int a = tableau.getSelectedColumn(); System.out.println("a"+ a); // // // String titl2[] = {"Nome shape"}; // // this.tableau = new JTable(data,titl2); //model.setRowHeight(30); //model.setNumRows(30); //On remplace cette ligne this.getContentPane().add(new JScrollPane(tableau), BorderLayout.CENTER); this.getContentPane().add(pan, BorderLayout.SOUTH); valider.addActionListener(this); pan.add(valider); }
9
public static void arc(double x, double y, double r, double angle1, double angle2) { if (r < 0) throw new RuntimeException("arc radius can't be negative"); while (angle2 < angle1) angle2 += 360; double xs = scaleX(x); double ys = scaleY(y); double ws = factorX(2*r); double hs = factorY(2*r); if (ws <= 1 && hs <= 1) pixel(x, y); else offscreen.draw(new Arc2D.Double(xs - ws/2, ys - hs/2, ws, hs, angle1, angle2 - angle1, Arc2D.OPEN)); show(); }
4
private void assignActionsToButtons() { glGlun.getDocument().addDocumentListener(new DocumentListener() { public void changedUpdate(DocumentEvent e) { updateButtonStates(); } public void removeUpdate(DocumentEvent e) { updateButtonStates(); } public void insertUpdate(DocumentEvent e) { updateButtonStates(); } }); bLoadFtedat.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { File f = FileUtil.showFtedatLoadDialog(controlPanel); if(f != null) { ftedat = f; ftedatLocation.setText(ftedat.getAbsolutePath()); updateButtonStates(); } } }); bLoad.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { File f = FileUtil.showSavegameLoadDialog(controlPanel); if(f != null) { savegame = f; savegameLocation.setText(savegame.getAbsolutePath()); updateButtonStates(); parseFile(); } } }); bRetry.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(savegame.getAbsolutePath().endsWith(".dat")) { parseFile(); } else { JOptionPane.showMessageDialog(controlPanel, "Something derped! Please try to select the file again.", "Derp", JOptionPane.WARNING_MESSAGE); } } }); bSave.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { editor.applyAllChanges(); } catch(Exception ex) { MessageUtil.error("Failed to Save:\n\n" + ex.getClass().toString() + ": " + ex.getMessage()); return; } File f = FileUtil.showSaveDialog(controlPanel, savegame); if(f != null) { storeFile(f); } } }); }
5
private void keepGettingFeatures(int count) { // If we're done, don't do anything else. if (count >= level) { return; } double data[]; int width = subImage.length; int height = subImage[0].length; // We're doing the same thing as above, but we're not working with a Raster anymore. double[][] firstPhaseOutput = new double[width][height]; double[][] secondPhaseOutput = new double[height][width]; double[][] thirdPhaseOutput = new double[width][height]; double[][] newSubImage = new double[width/2][height/2]; // Copy the array. // I thought java.util.Arrays would handle this, but I guess not... for (int x=0; x < width; x++) { for (int y=0; y < height; y++) { firstPhaseOutput[x][y] = subImage[x][y]; } } // First the columns. for (int x=0; x < width; x++) { data = firstPhaseOutput[x]; wavelet.daubTrans(data); for (int y=0; y < height; y++) { secondPhaseOutput[y][x] = data[y]; } } for (int y=0; y < height; y++) { data = secondPhaseOutput[y]; wavelet.daubTrans(data); for (int x=0; x < width; x++) { thirdPhaseOutput[x][y] += data[x]; } } subImage = new double[width/2][height/2]; double feature = 0; for (int x=0; x < width/2; x++) { for (int y=0; y < height/2; y++) { newSubImage[x][y] = thirdPhaseOutput[x][y]; feature += thirdPhaseOutput[x+(width/2)][y]; feature += thirdPhaseOutput[x][y+(height/2)]; feature += thirdPhaseOutput[x+(width/2)][y+(height/2)]; } } // Store the average energy level at this level of decomposition. feature /= (width * height/12.0); features[count] = feature; // Store the image to be used if we're going to do more levels of decomposition. subImage = newSubImage; // Do another level of deomposition if needed. keepGettingFeatures(count+1); }
9
@Test public void testAIWhatFinishLineWith2EnemyMarkInVosxodyawDiagonal() { Field field = new Field(); RulesOfGameAndLogic rog = new RulesOfGameAndLogic(field); field.eraseField(); int rand = (int)(Math.random()*2); int randINotSetCell = (int)(Math.random()*2); for (int i = 0, j = 2; i < 3; i++, j--) { if ((rand == 0)&(randINotSetCell != i)) { field.setCell(i, j, ZNACHENIE_POLYA_0); field.setLastInput(ZNACHENIE_POLYA_X); } else if (randINotSetCell != i) { field.setCell(i, j, ZNACHENIE_POLYA_X); field.setLastInput(ZNACHENIE_POLYA_0); } } if (field.getLastInput() == ZNACHENIE_POLYA_X) { field.setLastInput(ZNACHENIE_POLYA_0); } else { field.setLastInput(ZNACHENIE_POLYA_X); } rog.makeAMove(); assertEquals("Проверка на заполнение последней пустой ячейки (первой или второй) восходящей диагонали противоположным символом.",true, field.getCell(randINotSetCell, 2-randINotSetCell) == field.getLastInputH()); assertEquals("Проверка на заполнение восходящей диагонали после заполнения последней ячейки противоположным символом.",false,field.isFilledLine()); field.eraseField(); field.setLastInput(' '); rand = (int)(Math.random()*2); for (int i = 0, j = 2; i < 3; i++, j--) { if ((rand == 0) & ( i!=2 )) { field.setCell(i, j, ZNACHENIE_POLYA_0); field.setLastInput(ZNACHENIE_POLYA_X); } else if (i != 2) { field.setCell(i, j, ZNACHENIE_POLYA_X); field.setLastInput(ZNACHENIE_POLYA_0); } } if (field.getLastInput() == ZNACHENIE_POLYA_X) { field.setLastInput(ZNACHENIE_POLYA_0); } else { field.setLastInput(ZNACHENIE_POLYA_X); } rog.makeAMove(); assertEquals("Проверка на заполнение третьей ячейки в восходящей диагонали, при уже двух первых помеченных ячейках противоположной отметкой.",true, field.getCell(2, 0) == field.getLastInputH()); assertEquals("Проверка на заполнение восходящей диагонали после заполнения последней из трёх ячеек противоположной отметкой.",false,field.isFilledLine()); }
8
public static String formatNumber(int start) { DecimalFormat nf = new DecimalFormat("0.0"); double i = start; if(i >= 1000000) { return nf.format((i / 1000000)) + "m"; } if(i >= 1000) { return nf.format((i / 1000)) + "k"; } return ""+start; }
2
public Tour Mate(Tour t){ ArrayList<City> temp = t.tour; Integer random = (int) (Math.random()*tour.size()); ArrayList<City> child = new ArrayList<City>(tour.subList(0, random)); for(int i=0;i<child.size();i++){ temp.remove(child.get(i)); } for(City c:temp){ if(c!=null){ child.add(c); } } //Child cannot have null cities //child = new ArrayList<City>(child.subList(0, 30)); ArrayList<City> returnVal = new ArrayList<City>(30); for(City c:child){ if(c!=null){ returnVal.add(c); } } return new Tour(returnVal); }
5
public OperationExpression simplify() { if (((PrimitiveOperator) op).isComplexIDOfLeft()) { return new UnaryOpExpression(new PrimitiveOperator(PrimitiveOperator.ID_OP), left); } if (((PrimitiveOperator) op).isComplexNotOfLeft()) { return new UnaryOpExpression(new PrimitiveOperator(PrimitiveOperator.NOT_OP), left); } if (((PrimitiveOperator) op).isComplexIDOfRight()) { return new UnaryOpExpression(new PrimitiveOperator(PrimitiveOperator.ID_OP), right); } if (((PrimitiveOperator) op).isComplexNotOfRight()) { return new UnaryOpExpression(new PrimitiveOperator(PrimitiveOperator.NOT_OP), right); } if (((PrimitiveOperator) op).isComplexIDOfMiddle()) { return new UnaryOpExpression(new PrimitiveOperator(PrimitiveOperator.ID_OP), middle); } if (((PrimitiveOperator) op).isComplexNotOfMiddle()) { return new UnaryOpExpression(new PrimitiveOperator(PrimitiveOperator.NOT_OP), middle); } return this; //dammy }
6
public ArrayList<String> load(String csvFile) { BufferedReader br = null; String line = ""; String csvSplitBy = ","; data = new ArrayList<String>(); String[] tempArray=null; try { br = new BufferedReader(new FileReader(csvFile)); while ((line = br.readLine()) != null) { tempArray=line.split(csvSplitBy); } for (int i=0; i<tempArray.length;++i){ data.add(tempArray[i]); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } return data; }
6
public void renderHealth(int x, int y, int xOffset, int yOffset) { x <<= 5; y <<= 5; x = (int) (((x + xOffset) - camera.getXOffset())); y = (int) (((y + yOffset) - camera.getYOffset())); x += 2; y += 36; int barWidth = 29; int barHeight = 4; int[] bg = new int[barWidth * barHeight]; // Render the background of the bar (The black part) BufferedImage imageBG = new BufferedImage(barWidth, barHeight, BufferedImage.TYPE_INT_ARGB); Graphics2D g = (Graphics2D) imageBG.getGraphics(); g.setColor(Color.black); g.fillRect(0, 0, 1, 1); g.dispose(); int col = imageBG.getRGB(0, 0); Arrays.fill(bg, col); for (int yCounter = 0; yCounter < barHeight; yCounter++) { int ya = yCounter + y; for (int xCounter = 0; xCounter < barWidth; xCounter++) { int xa = xCounter + x; if (xa < -32 || xa >= width || ya < 0 || ya >= height) { break; } if (xa < 0) { xa = 0; } pixels[xa + ya * width] = bg[xCounter + yCounter * barWidth]; } } }
7
protected void calculateGlobalBest() { int best = 0; if(maximum){ for(int i = 0; i < fitness.size(); i++){ if(fitness.get(i) > fitness.get(best)){ best = i; } } }else{ for(int i = 0; i < fitness.size(); i++){ if(fitness.get(i) < fitness.get(best)){ best = i; } } } globalBest = best; }
5
public void hbasePreDispatch(List<Row> rows, List<StoreLoader<?>> rowLoaders, List<Increment> increments, List<StoreLoader<?>> incrementLoaders, byte[] familyName) { Put entityPutRow = new Put(getId().getKey().getBytes()); for (Map.Entry<Key, Data> column : getColumns().entrySet()) { entityPutRow.add(familyName, column.getKey().getBytes(), column.getValue().getBytes()); } rows.add(entityPutRow); rowLoaders.add(this); }
3
public static void main(String[] args) { Ex1 e1 = new Ex1(); System.out.println(e1); }
0
public String addMessage() throws Exception { System.out.println("userName is " + userName); Connection conn = null; int addCount = 0; Statement stmt = null; try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(url, user, psw); if (!conn.isClosed()) System.out.println("Success connecting to the Database!"); else System.out.println("Fail connecting to the Database!"); stmt = conn.createStatement(); addCount = stmt .executeUpdate("insert into message(user_name,message)" + "values('" + userName + "','" + message + "')"); if (addCount != 0) { showMessage(); return SUCCESS; } else { return ERROR; } } catch (Exception e) { System.out.print("connection error!"); e.printStackTrace(); return ERROR; } }
3
public void addBorder() { for (int i = 0; i < width(); i++) { for (int j = 0; j < height(); j++) { if (i == 0 || j == 0 || i == width() - 1 || j == height() - 1) maze[i][j] = 1; } } maze[1][0] = 0; maze[width() - 2][height() - 1] = 0; }
6
public Connection getConnection() { // System.out.println("-------- Mysql Connection Testing ------"); try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { System.out.println("Where is MySQL Driver?"); e.printStackTrace(); //return; } System.out.println("Mysql Driver Registered!"); Connection connection = null; try { connection = DriverManager.getConnection("jdbc:mysql://localhost/school","root",""); } catch (SQLException e) { System.out.println("Connection Failed! Check output console"); e.printStackTrace(); //return; } if (connection != null) { System.out.println("You made it, take control your database now!"); } else { System.out.println("Failed to make connection!"); } return connection ; }
3
public static int Str2Int(String str) { if (str == null || "".equals(str)) return 0; return Integer.parseInt(str); }
2
public static double[][] doubleSelectionSort(double[][] aa){ int index = 0; int lastIndex = -1; int n = aa[0].length; double holdx = 0.0D; double holdy = 0.0D; double[][] bb = new double[2][n]; for(int i=0; i<n; i++){ bb[0][i]=aa[0][i]; bb[1][i]=aa[1][i]; } while(lastIndex != n-1){ index = lastIndex+1; for(int i=lastIndex+2; i<n; i++){ if(bb[0][i]<bb[0][index]){ index=i; } } lastIndex++; holdx=bb[0][index]; bb[0][index]=bb[0][lastIndex]; bb[0][lastIndex]=holdx; holdy=bb[1][index]; bb[1][index]=bb[1][lastIndex]; bb[1][lastIndex]=holdy; } return bb; }
4
public static Status getEnum(String value) { if (value == null) { throw new IllegalArgumentException(); } for (Status v : values()) { if (value.equalsIgnoreCase(v.getValue())) { return v; } } throw new IllegalArgumentException(); }
3
public void aumentarTiempoEnEspera() { if (numProcesos != 0) { for (int i = menorPrioridadNoVacia; i < listas.length; i++) { for (int j = 0; j < listas[i].size(); j++) { listas[i].get(j).aumentarTiempoEnEspera(); } } } }
3
public static String getTypeValById(Integer id) { switch (id) { case TYPE_DATE: return "dateval"; case TYPE_FLOAT: return "floatval"; case TYPE_INT: return "intval"; case TYPE_LIST: return "listval"; case TYPE_STR: return "strval"; case TYPE_TEXT: return "textval"; } return "strval"; }
6
public static void alteraContato(String nome, String novonome, String novoendereco, String novotel) throws FileNotFoundException, IOException { StringBuilder sb = new StringBuilder(); InputStream is = new FileInputStream("Contatos.txt"); PrintStream qs = new PrintStream("Auxiliar.txt"); Scanner entrada = new Scanner(is); String l, texto; while (entrada.hasNextLine()) { l = entrada.nextLine(); String vetor[] = l.split("@"); if (!vetor[0].equals(nome)) { sb.append(String.format("%s@%s@%s", vetor[0], vetor[1], vetor[2])); qs.println(sb.toString()); sb.setLength(0); } if(vetor[0].equals(nome)){ sb.append(String.format("%s@%s@%s", novonome, novoendereco, novotel)); qs.println(sb.toString()); sb.setLength(0); } } PrintStream ps = new PrintStream("Contatos.txt"); InputStream es = new FileInputStream("Auxiliar.txt"); Scanner entrada2 = new Scanner(es); while (entrada2.hasNextLine()) { ps.println(entrada2.nextLine()); } ps.close(); es.close(); is.close(); }
4
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // CHANGE: The EJB is instantiated automatically // CourseModel model = CourseModelImpl.getInstance(); String path = request.getServletPath(); if (path.equals("/ProgramController")) { try { String studentId = request.getParameter("studentId"); StudentMark[] marks = model.getAllStudentMarks(studentId); Student student = model.getStudent(studentId); request.setAttribute("marks", marks); request.setAttribute("student", student); } catch (CourseException ex) { request.setAttribute("message", ex.getMessage()); }; RequestDispatcher dispatcher = request.getRequestDispatcher("ProgramDetails.jsp"); dispatcher.forward(request, response); } else if (path.equals("/AllModules")) { try { Module[] modules = model.getAllModules(); request.setAttribute("modules", modules); } catch (CourseException ex) { request.setAttribute("message", ex.getMessage()); } RequestDispatcher dispatcher = request.getRequestDispatcher("AllModules.jsp"); dispatcher.forward(request, response); } }
4
public KeyInfoType getEncryptionKey() { return encryptionKey; }
0
public void Jouer() { afficherInfosDebutTour(); Joueur j; for(IndexJoueurCourant = 0; IndexJoueurCourant < this.joueurs.size(); IndexJoueurCourant++){ int nbdoble=1; j = this.joueurs.get(IndexJoueurCourant); j.avancer(); afficherInfosJoueur(j); j.getPositionCourante().execute(j); while(j.getDes()[0]==j.getDes()[1] && nbdoble<3){ j.avancer(); afficherInfosJoueur(j); if(nbdoble==2 && j.getDes()[0]==j.getDes()[1]){ envoiePrison(j); } else {j.getPositionCourante().execute(j);} nbdoble++; } } System.out.println("========================== Continuer ? (y/n) ===================== (else = y)"); if("n".equals(sc.nextLine())){ this.joueurs.clear(); } }
6