text
stringlengths
14
410k
label
int32
0
9
private Symbol tryDeclareSymbol(Token ident) { assert (ident.isToken(Token.Kind.IDENTIFIER)); String name = ident.lexeme; try { return symbolTable.insert(name); } catch (RedeclarationError re) { String message = reportDeclareSymbolError(name, ident.lineNumber, ident.charPosition); return new ErrorSymbol(message); } }
1
public Quaternion slerp( Quaternion dest, float lerpFactor, boolean shortest ) { final float EPSILON = 1e3f; float cos = this.dot( dest ); Quaternion correctedDest = dest; if ( shortest && cos < 0 ) { cos = -cos; correctedDest = new Quaternion( -dest.getX(), -dest.getY(), -dest.getZ(), -dest.getW() ); } if ( Math.abs( cos ) >= 1 - EPSILON ) return nlerp( correctedDest, lerpFactor, false ); float sin = (float) Math.sqrt( 1.0f - cos * cos ); float angle = (float) Math.atan2( sin, cos ); float invSin = 1.0f / sin; float srcFactor = (float) Math.sin( ( 1.0f - lerpFactor ) * angle ) * invSin; float destFactor = (float) Math.sin( ( lerpFactor ) * angle ) * invSin; return this.mul( srcFactor ).add( correctedDest.mul( destFactor ) ); }
3
private static void ensembleMethodOverlap() throws ParserConfigurationException, Exception { Scanner sc = new Scanner(System.in); System.out.println("How many systems for the ensemble?"); int numSystems = sc.nextInt(); //sc.close(); ArrayList<String> testSets[] = new ArrayList[numSystems]; AbstractResultSet resSets[] = new AbstractResultSet[numSystems]; String testTypes[] = new String[numSystems]; System.out.println("Select Gold Standard data set:"); String gold = promptForPathSelection(EVALUATION_HOME); for(int i = 0; i < numSystems; i++) { System.out.println("Select Test Set " + i+1); testTypes[i] = promptForPathSelection(EVALUATION_HOME); testSets[i] = EvaluatorUtil.getPathsInFolder(EVALUATION_HOME + testTypes[i]); } System.out.println("output filename:"); String filename = CSV_HOME + new Scanner(System.in).nextLine(); PrintWriter out = new PrintWriter(new File(filename)); ArrayList<String> goldSet = EvaluatorUtil.getPathsInFolder(EVALUATION_HOME + gold); AbstractResultSet goldres1; String filter = getFilterOption(); String csv_header = "docnum"; String ME = ""; String SB = ""; String AO = ""; for(int i = numSystems; i > 0; i--) { ME += ",ME_tp_"+i; SB += ",SB_tp_"+i; AO += ",AO_tp_"+i; } csv_header +=ME+",ME_fn"+SB+",SB_fn"+AO+",AO_fn,totalConcepts\n"; out.write(csv_header); Match matchOrder[] = {Match.EXACT_MATCH,Match.SINGLE_BOUNDARY,Match.ANY_OVERLAP}; for(int i=0; i< testSets[0].size(); i++) { int docNum = getResSet(testTypes[0],testSets[0].get(i)).docNumber; System.out.println(docNum); for(int j = 0; j <numSystems; j++) { resSets[j] = getResSet(testTypes[j],getResultsFileByNum(docNum,testSets[j])); if(filter != null) resSets[j].filter(filter); } goldres1 = getResSet(gold,getResultsFileByNum(docNum,goldSet)); if(filter != null) { System.out.println("Filtering for: " + filter); goldres1.filter(filter); } out.print(docNum); int[] combinedDistributions; for(Match criterion : matchOrder) { combinedDistributions = getCombinedDistribution(goldres1,resSets,criterion); for(int dist : combinedDistributions) out.printf(",%d", dist); for(AbstractResultSet res : resSets) res.reset(); } out.printf(",%d\n",goldres1.concepts.size()); System.out.println(i); } out.close(); }
9
@Override public void invoke(ChatSocket socket) throws InvalidCommandException { // Sanity check the command if (present && socket.getPresenceManager().isPresent(roomName, socket.getUUID())) { throw new InvalidCommandException("Could not join " + roomName + ": Already present."); } if (!present && !socket.getPresenceManager().isPresent(roomName, socket.getUUID())) { throw new InvalidCommandException("Could not leave " + roomName + ": Not present."); } // Setup the UserPresenceMessage socket.getPresenceManager().setPresence(roomName, socket.getUUID(), present); PresenceStatus status = present ? PresenceStatus.JOIN : PresenceStatus.LEAVE; try { socket.sendPacket(socket.wrapPayload(new UserPresenceMessage(roomName, status))); // If the client is joining a room, bring the them up to date by // pushing previous messages if (status == PresenceStatus.JOIN) { for (ChatPacket p : socket.getPersistenceManager().getRoomMessages(roomName)) { socket.pushToClient(p, true); } } } catch (IOException e) { throw new InvalidCommandException("Unable to send presence packet."); } }
8
public ScreenManager() { GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment(); device = environment.getDefaultScreenDevice(); }
0
public ArrayList<Tree> findLoopControlStatements(){ ArrayList<Tree> loopControlstatements = new ArrayList<Tree>(); if(this.statement instanceof LoopControlStatement) loopControlstatements.add(this.statement); if(this.statements instanceof LoopControlStatement) loopControlstatements.add(this.statements); if(this.statements instanceof Statements) loopControlstatements.addAll(((Statements)this.statements).findLoopControlStatements()); return loopControlstatements; }
3
@Override public boolean equals(Object object) { if (object == this) { return true; } if (object == null || !(object instanceof AABB3)) { return false; } AABB3 aabb = (AABB3) object; return aabb.x1 == x1 && aabb.y1 == y1 && aabb.z1 == z1 && aabb.x2 == x2 && aabb.y2 == y2 && aabb.z2 == z2; }
8
@Override public Boolean save(ModelUser oUser) { try { if (oUser.getId() != null) { if (oUser.getPassword() == null || oUser.getPassword().equals("") || oUser.getPassword().equals("********")) { String password = this.getById(oUser.getId()).getPassword(); oUser.setPassword(password); } this.update(oUser); } else { this.insert(oUser); } return true; } catch (Exception e) { return false; } }
5
private void foo(String str, int starts, int ends, ArrayList<String> result) { if (starts > ends) return; if (starts < 0) return; if (starts == 0 && ends == 0) { result.add(str); return; } foo(str + '(', starts - 1, ends, result); foo(str + ')', starts, ends - 1, result); }
4
final boolean method2535(AbstractToolkit var_ha, long l) { if (aLong6472 != aLong6471) method2534(); else method2537(); if (l - aLong6472 > 750L) { method2530(); return false; } int i = (int) (l - aLong6471); if (aBoolean6484) { for (Class318_Sub7 class318_sub7 = (Class318_Sub7) aClass243_6478.method1872(8); class318_sub7 != null; class318_sub7 = (Class318_Sub7) aClass243_6478.method1878((byte) 122)) { for (int i_4_ = 0; i_4_ < ((Class181) (((Class318_Sub7) class318_sub7) .aClass181_6441)).anInt2422; i_4_++) class318_sub7.method2513(var_ha, 1, l, 3, !aBoolean6473); } aBoolean6484 = false; } for (Class318_Sub7 class318_sub7 = (Class318_Sub7) aClass243_6478.method1872(8); class318_sub7 != null; class318_sub7 = (Class318_Sub7) aClass243_6478.method1878((byte) -72)) class318_sub7.method2513(var_ha, i, l, 3, !aBoolean6473); aLong6471 = l; return true; }
6
@Override public List<Node> shortestPath(Node source, Node dest) throws IOException { // System.out.println("Calling shortestPath."); LinkedList<Node> list = null; String input = null; try { StringBuilder sb = new StringBuilder("shortestPath\n"); sb.append(ProtocolParser.encodeEmptyNode(source)); sb.append(ProtocolParser.encodeEmptyNode(dest)); String output = ProtocolParser.appendLineCount(sb.toString()); writer.print(output); writer.flush(); int lines = Integer.parseInt(reader.readLine().trim()); sb = new StringBuilder(); for (int i = 0; i < lines; i++) { String line = reader.readLine().trim(); sb.append(line); sb.append("\n"); } input = sb.toString(); } catch (IOException e){ System.err.println("ERROR: problem interacting with server."); System.err.println(e.getMessage()); } catch (NullPointerException e) { System.err.println("ERROR: not receiving server response."); } if (input != null) if (input.startsWith("List")) { List<Object> rawList = ProtocolParser.decodeList(input); list = new LinkedList<Node>(); for (Object o : rawList) { if (o instanceof Node) { list.add((Node) o); } else { System.err.println("ERROR: Should be getting a list of nodes from Client.shortestPath, but not."); } } } else if (input.startsWith("IOException")) { throw ProtocolParser.decodeIOException(input); } return list; }
8
@Basic @Column(name = "SOL_FECHA_HORA") public Date getSolFechaHora() { return solFechaHora; }
0
public MobileScriptBuilder() { initialize(); // Perform these after UI setup try { createDependencies(); } catch (Exception e) { Helpers.showExceptionError(frmPswgToolsMbs, e.getLocalizedMessage());} // Populate Default Attacks combobox Vector<String> defaultAttacks = new Vector<String>(); try(BufferedReader br = new BufferedReader(new FileReader("./defaultAttacks.txt"))) { for(String line; (line = br.readLine()) != null; ) { if (line.equals("") || line.equals(" ")) continue; defaultAttacks.add(line); } } catch (Exception e) { Helpers.showExceptionError(frmPswgToolsMbs, e.getLocalizedMessage());} cmbDefaultAttack.setModel(new DefaultComboBoxModel<String>(defaultAttacks)); // Populate Mobiles Tree if (coreLocation != null && coreLocation != "" && !mobilesLoaded) { populateMobilesTree(new File(coreLocation + "\\scripts\\mobiles")); } instance = this; // Load additional UI's weaponTempDialog = new WeaponTemplateDialog(); }
8
public static List<FreightBean> get56(String oringHarborName,String destHarborName){ List<FreightBean> retFreightBeans = new ArrayList<FreightBean>(); HttpClient httpClient = new HttpClient(); httpClient.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 50000); httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(500000); PostMethod postMethod = new PostMethod("http://www.get56.com/get56n/freight/editFreight.php?actioncode=getfreightcase"); postMethod.addRequestHeader("Accept", "*/*"); //postMethod.addRequestHeader("Accept-Encoding", "gzip,deflate,sdch"); postMethod.addRequestHeader("Accept-Language", "en,zh-CN;q=0.8,zh;q=0.6"); postMethod.addRequestHeader("Cache-Control", "no-cache"); postMethod.addRequestHeader("Connection", "keep-alive"); //postMethod.addRequestHeader("Content-Length", "112"); postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;utf-8"); //postMethod.addRequestHeader("Cookie", "JSESSIONID=35329BC1829FA649C3D9EA4113BFEAE7; IESESSION=alive; JSESSIONID=CA92884903CAD4E355E19BC9FD0767DF; _ga=GA1.2.1561237817.1408674593"); postMethod.addRequestHeader("Host", "www.get56.com"); postMethod.addRequestHeader("Pragma", "no-cache"); postMethod.addRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143 Safari/537.36"); postMethod.addRequestHeader("X-Requested-With", "XMLHttpRequest"); postMethod.addRequestHeader("Origin", "http://www.get56.com"); postMethod.addRequestHeader("Referer", "http://www.get56.com/get56n/logistics/onestop.shtml"); postMethod.addParameter("page", "1"); postMethod.addParameter("pagesize", "10"); postMethod.addParameter("stport", oringHarborName);//"CNSHA"); postMethod.addParameter("end_port", destHarborName);//"30996"); String startDate = Common.nowDate("yyyy-MM-dd"); postMethod.addParameter("start_date", startDate); postMethod.addParameter("start_date_end", ""); postMethod.addParameter("gp20num", "1"); postMethod.addParameter("gp40num", ""); postMethod.addParameter("hc40num", ""); try { //get json from get56.com httpClient.executeMethod(postMethod); //System.out.println(postMethod.getResponseBodyAsString()); String jsonString = postMethod.getResponseBodyAsString(); Type type = new TypeToken<Get56Bean>(){}.getType(); Gson gson = new GsonBuilder().registerTypeAdapterFactory(new ArrayAdapterFactory()).create(); Get56Bean get56Bean = gson.fromJson(jsonString, type); //parser data into pojo int get56BeanPageCount = get56Bean.getPageCount(); int get56BeanTotalCount = get56Bean.getTotalCount(); int get56ResultSize = get56Bean.getResult().size(); ArrayList<Get56ResultBean> get56ResultBeans = (ArrayList<Get56ResultBean>) get56Bean.getResult(); for(int get56ResultBeanIndex =0;get56ResultBeanIndex < get56ResultSize; get56ResultBeanIndex++) { Get56ResultBean get56ResultBean = get56ResultBeans.get(get56ResultBeanIndex); FreightBean freightBean = Converter.get56Bean2FreightBean(get56ResultBean); freightBean.setOringHarborName(oringHarborName); freightBean.setDestHarborName(destHarborName); if (freightBean.getCarrier()!=null) { retFreightBeans.add(freightBean); } } // turn page operation. if ( get56BeanPageCount > 1) { for(int pageIndex=2;pageIndex<=get56BeanPageCount;pageIndex++) { Thread.sleep(10000); postMethod.setParameter("page", Integer.toString(pageIndex)); httpClient.executeMethod(postMethod); jsonString = postMethod.getResponseBodyAsString(); get56Bean = gson.fromJson(jsonString, type); //parser data into pojo get56ResultSize = get56Bean.getResult().size(); get56ResultBeans = (ArrayList<Get56ResultBean>) get56Bean.getResult(); for(int get56ResultBeanIndex =0;get56ResultBeanIndex < get56ResultSize; get56ResultBeanIndex++) { Get56ResultBean get56ResultBean = get56ResultBeans.get(get56ResultBeanIndex); FreightBean freightBean = Converter.get56Bean2FreightBean(get56ResultBean); freightBean.setOringHarborName(oringHarborName); freightBean.setDestHarborName(destHarborName); if (freightBean.getCarrier()!=null) { retFreightBeans.add(freightBean); } } } } } catch (HttpException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } return retFreightBeans; }
9
private final String stringFilter( String line ) { if ( line == null || line.equals( "" ) ) { return ""; } StringBuffer buf = new StringBuffer(); if ( line.indexOf( "\"" ) <= -1 ) { return keywordFilter( line ); } int start = 0; int startStringIndex = -1; int endStringIndex = -1; int tempIndex; //Keep moving through String characters until we want to stop... while ( ( tempIndex = line.indexOf( "\"" ) ) > -1 ) { //We found the beginning of a string if ( startStringIndex == -1 ) { startStringIndex = 0; buf.append( stringFilter( line.substring( start, tempIndex ) ) ); buf.append( STRING_START ).append( "\"" ); line = line.substring( tempIndex + 1 ); } //Must be at the end else { startStringIndex = -1; endStringIndex = tempIndex; buf.append( line.substring( 0, endStringIndex + 1 ) ); buf.append( STRING_END ); line = line.substring( endStringIndex + 1 ); } } buf.append( keywordFilter( line ) ); return buf.toString(); }
5
public boolean equals(Object o) { return (o instanceof TreeElement) && fullName.equals(((TreeElement) o).fullName); }
1
private void makeDiagonalMove(Player player) { int diagonalDown = 0; int diagonalUp = 0; for(int i = 0; i < 3; i++) { if(this.gameField.getGameField()[i][i] == player) { diagonalDown++; } if(this.gameField.getGameField()[2-i][i] == player) { diagonalUp++; } } // make move in the first diagonal if(diagonalDown == 2) { for(int i = 0; i < 3; i++) { if(this.gameField.getGameField()[i][i] == null) { this.gameField.getGameField()[i][i] = computer; this.nextMove = i*3 + i + 1; } } } // make move in the second diagonal if(diagonalUp == 2) { for(int i = 0; i < 3; i++) { if(this.gameField.getGameField()[2-i][i] == null) { this.gameField.getGameField()[2-i][i] = computer; this.nextMove = (7 - (2*i)); } } } }
9
public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); System.out.print("Please enter x: "); double x = keyboard.nextDouble(); int terms = 0; while (terms == 0) { System.out.print("Please enter the number of terms, an integer (>1 and <64): "); terms = keyboard.nextInt(); if (terms <= 1 || terms >= 64) { terms = 0; System.out.println("You must enter an integer greater than 1 and less than 64."); } } double exp = 1; long factorial = 1; for (int count = 1; count < terms; count++) { factorial *= count; exp += Math.pow(x,count)/factorial; } System.out.println("The approximation of exp(" + x + ") using " + terms + " terms is " + exp); }
4
public static String toString(JSONObject jo) throws JSONException { StringBuffer sb = new StringBuffer(); sb.append(escape(jo.getString("name"))); sb.append("="); sb.append(escape(jo.getString("value"))); if (jo.has("expires")) { sb.append(";expires="); sb.append(jo.getString("expires")); } if (jo.has("domain")) { sb.append(";domain="); sb.append(escape(jo.getString("domain"))); } if (jo.has("path")) { sb.append(";path="); sb.append(escape(jo.getString("path"))); } if (jo.optBoolean("secure")) { sb.append(";secure"); } return sb.toString(); }
4
private void Speedup(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Speedup if (currSpeed < 10) { ++currSpeed; world.setSpeed(currSpeed); speedCounter.setText("Speed: " + currSpeed); } }//GEN-LAST:event_Speedup
1
protected static final synchronized void putCachedRaster(ColorModel cm, WritableRaster ras) { if (cached != null) { WritableRaster cras = (WritableRaster) cached.get(); if (cras != null) { int cw = cras.getWidth(); int ch = cras.getHeight(); int iw = ras.getWidth(); int ih = ras.getHeight(); if (cw >= iw && ch >= ih) { return; } if (cw * ch >= iw * ih) { return; } } } cachedModel = cm; cached = new WeakReference(ras); }
5
public static void removeFromListById(List<AchievementRecord> achList, String achievementId) { for ( ListIterator<AchievementRecord> it = achList.listIterator(); it.hasNext(); ) { AchievementRecord rec = it.next(); if ( rec.getAchievementId().equals(achievementId) ) { it.remove(); } } }
2
public boolean get_mbr(){ if (!proj_IA_network_x.calculate() || !proj_IA_network_y.calculate()){ return false;} //if any of the IA networks is unsatisfiable, return false mbr = new Rectangle[var_num]; for(int i=0;i<var_num;i++){ mbr[i] = new Rectangle(); } //Arrays.fill(mbr, new Rectangle()); maxX=0;maxY=0; for (int i=0;i<var_num;i++) { mbr[i].x.i1=proj_IA_network_x.sol[i].i1; mbr[i].x.i2=proj_IA_network_x.sol[i].i2; if (mbr[i].x.i2>maxX) maxX=mbr[i].x.i2; mbr[i].y.i1=proj_IA_network_y.sol[i].i1; mbr[i].y.i2=proj_IA_network_y.sol[i].i2; if (mbr[i].y.i2>maxY) maxY=mbr[i].y.i2; } //[0,max_x]*[0,max_y] is the frame, i.e., the smallest rectangle containing all the mbrs return true; }
6
public void color(int i, int x, int y) { if(x < texture.getWidth() && y < texture.getHeight() && x >= 0 && y >= 0) { texture.setRGB(x, y, new Color(i).getRGB()); this.repaint(); } }
4
public IVPBoolean ivpEqualTo(IVPValue num, Context c, HashMap map, DataFactory factory) { IVPBoolean result = factory.createIVPBoolean(); map.put(result.getUniqueID(), result); boolean resultBoolean = false; if(getValueType().equals(IVPValue.INTEGER_TYPE) && num.getValueType().equals(IVPValue.INTEGER_TYPE)){ resultBoolean = c.getInt(getUniqueID()) == c.getInt(num.getUniqueID()); }else{ if(getValueType().equals(IVPValue.DOUBLE_TYPE) && num.getValueType().equals(IVPValue.DOUBLE_TYPE)){ resultBoolean = c.getDouble(getUniqueID()) == c.getDouble(num.getUniqueID()); }else{ if(getValueType().equals(IVPValue.DOUBLE_TYPE)){ resultBoolean = c.getDouble(getUniqueID()) == c.getInt(num.getUniqueID()); }else{ resultBoolean = c.getInt(getUniqueID()) == c.getDouble(num.getUniqueID()); } } } c.addBoolean(result.getUniqueID(), resultBoolean); return result; }
5
public static String extractAlbumFrom(String filePath) /* * The extractAlbumFrom method checks the ID3 version of the mp3 file and * extracts the artist's name from the MP3 file. */ { String albumName = null; try { Mp3File mp3File = new Mp3File(filePath); if (mp3File.hasId3v2Tag()) { ID3v2 id3v2Tag = mp3File.getId3v2Tag(); albumName = id3v2Tag.getAlbum(); } else if (mp3File.hasId3v1Tag()) { ID3v1 id3v1Tag = mp3File.getId3v1Tag(); albumName = id3v1Tag.getAlbum(); } } catch (UnsupportedTagException e) { e.printStackTrace(); } catch (InvalidDataException e) { System.out.print("Invalid Data"); return " - Unknown Album"; //e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { if(albumName.equals(null)) albumName = "Unknown Album"; } catch (Exception e) {albumName = "Unknown Album"; //e.printStackTrace(); } return albumName; }
7
public static void sort(Comparable[] a){ for(int i = 0; i < a.length; i++){ int k = i; for(int j = i + 1; j < a.length; j++){ if(a[j].compareTo(a[k]) < 0){ k = j; } } if( k == i) continue; Comparable tmp = a[k]; a[k] = a[i]; a[i] = tmp; } }
4
private byte[] rehash(byte[] passwordHash, byte[] salt) { try { MessageDigest md = MessageDigest.getInstance("SHA-256"); byte[] bytes = new byte[passwordHash.length + salt.length]; // Join passwordHash and salt together into a single array, seed System.arraycopy(passwordHash, 0, bytes, 0, passwordHash.length); System.arraycopy(salt, 0, bytes, passwordHash.length, salt.length); // Do some key stretching for (int i = 0; i < hashStretchFactor; i++) { md.update(bytes); bytes = md.digest(); } return bytes; } catch (NoSuchAlgorithmException ex) { Alerter.getHandler().severe("Authetication", "Unable to re-hash password for saving. " + ex.getMessage()); return null; } }
2
public void terminateSesion() { endSesion = true; try { clientSocket.close(); clientSocket = null; } catch (IOException e) { e.printStackTrace(); } }
1
@Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Medico)) { return false; } Medico other = (Medico) object; if ((this.idMedico == null && other.idMedico != null) || (this.idMedico != null && !this.idMedico.equals(other.idMedico))) { return false; } return true; }
5
public static void main(String[] args) { int[][] array = new Spiral_Matrix_II().generateMatrix(6); for(int i=0;i< array[0].length;i++) System.out.println(Arrays.toString(array[i])); }
1
private boolean isStoppingCriterionNotMet(int currentIteration) { if (!UserStopCondition.shouldStop()) { if (isStoppingCriterion) { return (population.getBestFitness() > FITNESS_THRESHOLD); } else { return ((maxIterations == 0) || (currentIteration < maxIterations)); } } else { return false; } }
3
public boolean step(Point where) { Viewport port = findViewport(owner); Rectangle rect = Rectangle.SINGLETON; port.getClientArea(rect); port.translateToParent(rect); port.translateToAbsolute(rect); if (!rect.contains(where) || rect.crop(threshold).contains(where)) return false; // set scroll offset (speed factor) int scrollOffset = 0; // calculate time based scroll offset if (lastStepTime == 0) lastStepTime = System.currentTimeMillis(); long difference = System.currentTimeMillis() - lastStepTime; if (difference > 0) { scrollOffset = ((int) difference / 3); lastStepTime = System.currentTimeMillis(); } if (scrollOffset == 0) return true; rect.crop(threshold); int region = rect.getPosition(where); Point loc = port.getViewLocation(); if ((region & PositionConstants.SOUTH) != 0) loc.y += scrollOffset; else if ((region & PositionConstants.NORTH) != 0) loc.y -= scrollOffset; if ((region & PositionConstants.EAST) != 0) loc.x += scrollOffset; else if ((region & PositionConstants.WEST) != 0) loc.x -= scrollOffset; port.setViewLocation(loc); return true; }
9
public AttributeResource(int id) { this.attributeID = id; }
0
protected WordText buildSpaceWord(GlyphText sprite) { // because we are in a normalized user space we can work with ints Rectangle2D.Float bounds1 = currentGlyph.getBounds(); Rectangle.Float bounds2 = sprite.getBounds(); float space = bounds2.x - (bounds1.x + bounds1.width); // max width of previous and next glyph, average can be broken by l or i etc. float maxWidth = Math.max(bounds1.width, bounds2.width) / 2f; int spaces = (int) (space / maxWidth); spaces = spaces < 1 ? 1 : spaces; float spaceWidth = space / spaces; // add extra spaces WordText whiteSpace = new WordText(); double offset = bounds1.x + bounds1.width; GlyphText spaceText; Rectangle2D.Float spaceBounds = new Rectangle2D.Float( bounds1.x + bounds1.width, bounds1.y, spaceWidth, bounds1.height); // todo: consider just using one space with a wider bound // Max out the spaces in the case the spaces value scale factor was // not correct. We can end up with a very large number of spaces being // inserted in some cases. for (int i = 0; i < spaces && i < 50; i++) { spaceText = new GlyphText((float) offset, currentGlyph.getY(), new Rectangle2D.Float(spaceBounds.x, spaceBounds.y, spaceBounds.width, spaceBounds.height), String.valueOf((char)32), String.valueOf((char)32)); spaceBounds.x += spaceBounds.width; whiteSpace.addText(spaceText); whiteSpace.setWhiteSpace(true); offset += spaceWidth; } return whiteSpace; }
3
@Path("editUser.html") @Produces(MediaType.TEXT_HTML) @GET public Response getEditUserView(@CookieParam("authUser") String token, @QueryParam("message") String message, @QueryParam("userName") String userName) { try { UserToken verifiedUserToken = doVerifyUserToken(token); //Make sure they are logged in if (verifiedUserToken == null) { return Response.seeOther(new URI(LOGIN_HTML.toString() + "?destination=" + URLEncoder.encode(serviceBaseURL + "editUser.html?userName="+userName, "utf8"))).cacheControl(NO_CACHE_CONTROL).cookie(newEmptyExpiredCookie()).build(); } //Make sure they have the useradmin role if (!verifiedUserToken.userAccount.hasRole("UserAdmin")) { return Response.seeOther(PERMISSION_DENIED_HTML).cacheControl(NO_CACHE_CONTROL).cookie(newEmptyExpiredCookie()).build(); } //Make sure there is a user parameter if (Strings.isNullOrEmpty(userName)){ return Response.seeOther(new URI(serviceBaseURL+"manageUsers.html?message=" + URLEncoder.encode("Woops, no user was selected to edit","utf8"))).cacheControl(NO_CACHE_CONTROL).build(); } //Check that the user is a real user UserAccount user = dataStore.getUser(userName); if (user==null) { return Response.seeOther(new URI(serviceBaseURL + "manageUsers.html?message=" + URLEncoder.encode("Woops, invalid user was selected to edit", "utf8"))).cacheControl(NO_CACHE_CONTROL).build(); } List<Role> assignableRoles = new ArrayList<Role>(); for (Role role : dataStore.getRoles()) { if (isRoleAssignableByUser(role, verifiedUserToken)) { assignableRoles.add(role); } } return Response.ok().cacheControl(NO_CACHE_CONTROL).entity(new EditUserView(verifiedUserToken, user, assignableRoles, message)).build(); } catch (Exception e) { throw new WebApplicationException(Response.serverError().cacheControl(NO_CACHE_CONTROL).cookie(newEmptyExpiredCookie()).build()); } }
7
@Override public boolean decideDraw(int turn) { int[] votes = new int[2]; for (Model m: ensemble) votes[m.decideDraw(turn) ? 1 : 0]++; return votes[1] > votes[0]; }
2
private void verificarInvariante() { int i,x1,y1,x2,y2 ; ArrayList<Integer> actual; Nodo nodoAEvaluar; Nodo posibleAdyacente; int N=(int) Math.sqrt(V); for(i = 0; i< V; i++){ actual=adj(i); x1=i%N; y1=(i-x1)/N; nodoAEvaluar=malla[y1][x1]; for (Integer j : actual) { x2=j%N; y2=(j-x2)/N; posibleAdyacente=malla[y2][x2]; if(!nodoAEvaluar.esAdyacenteA(posibleAdyacente)){ System.err.println("Error en posición "+i+" de lista."); } } } }
3
public static void main(String[] args) { System.out.println("Starting network example ..."); try { ////////////////////////////////////////// // First step: Initialize the GridSim package. It should be called // before creating any entities. We can't run this example without // initializing GridSim first. We will get run-time exception // error. int num_user = 2; // number of grid users Calendar calendar = Calendar.getInstance(); // a flag that denotes whether to trace GridSim events or not. boolean trace_flag = true; // Initialize the GridSim package System.out.println("Initializing GridSim package"); GridSim.init(num_user, calendar, trace_flag); ////////////////////////////////////////// // Second step: Creates one or more GridResource entities double baud_rate = 1000; // bits/sec double propDelay = 10; // propagation delay in millisecond int mtu = 1500; // max. transmission unit in byte int i = 0; // more resources can be created by // setting totalResource to an appropriate value int totalResource = 1; ArrayList resList = new ArrayList(totalResource); for (i = 0; i < totalResource; i++) { GridResource res = createGridResource("Res_"+i, baud_rate, propDelay, mtu); // add a resource into a list resList.add(res); } ////////////////////////////////////////// // Third step: Creates one or more grid user entities // number of Gridlets that will be sent to the resource int totalGridlet = 5; // create users ArrayList userList = new ArrayList(num_user); ArrayList userNameList = new ArrayList(); // for background traffic for (i = 0; i < num_user; i++) { String name = "User_" + i; // if trace_flag is set to "true", then this experiment will // create User_i.csv where i = 0 ... (num_user-1) NetUser user = new NetUser(name, totalGridlet, baud_rate, propDelay, mtu, trace_flag); // add a user into a list userList.add(user); userNameList.add(name); } ////////////////////////////////////////// // Fourth step: Builds the network topology among entities. // In this example, the topology is: // user(s) --1Mb/s-- r1 --10Mb/s-- r2 --1Mb/s-- GridResource(s) // create the routers. // If trace_flag is set to "true", then this experiment will create // the following files (apart from sim_trace and sim_report): // - router1_report.csv // - router2_report.csv Router r1 = new RIPRouter("router1", trace_flag); // router 1 Router r2 = new RIPRouter("router2", trace_flag); // router 2 // generates some background traffic using SimJava2 distribution // package. NOTE: if you set the values to be too high, then // the simulation might finish longer TrafficGenerator tg = new TrafficGenerator( new Sim_uniform_obj("freq",1,3), // num of packets new Sim_uniform_obj("inter_arrival_time",10,20) ); // connect all user entities with r1 with 1Mb/s connection // For each host, specify which PacketScheduler entity to use. NetUser obj = null; for (i = 0; i < userList.size(); i++) { // A First In First Out Scheduler is being used here. // SCFQScheduler can be used for more fairness FIFOScheduler userSched = new FIFOScheduler("NetUserSched_"+i); obj = (NetUser) userList.get(i); r1.attachHost(obj, userSched); // for even user number if (i % 2 == 0) { // for each time, sends junk packet(s) to all entities tg.setPattern(TrafficGenerator.SEND_ALL); // sends junk packet(s) to resource and user entities obj.setBackgroundTraffic(tg, userNameList); } else // for odd user number { // for each time, sends junk packet(s) to only one entity tg.setPattern(TrafficGenerator.SEND_ONE_ONLY); // sends junk packet(s) to resource entities only obj.setBackgroundTraffic(tg); } } // connect all resource entities with r2 with 1Mb/s connection // For each host, specify which PacketScheduler entity to use. GridResource resObj = null; for (i = 0; i < resList.size(); i++) { FIFOScheduler resSched = new FIFOScheduler("GridResSched_"+i); resObj = (GridResource) resList.get(i); r2.attachHost(resObj, resSched); } // then connect r1 to r2 with 10Mb/s connection // For each host, specify which PacketScheduler entity to use. baud_rate = 10000; Link link = new SimpleLink("r1_r2_link", baud_rate, propDelay, mtu); FIFOScheduler r1Sched = new FIFOScheduler("r1_Sched"); FIFOScheduler r2Sched = new FIFOScheduler("r2_Sched"); // attach r2 to r1 r1.attachRouter(r2, link, r1Sched, r2Sched); ////////////////////////////////////////// // Fifth step: Starts the simulation GridSim.startGridSimulation(); ////////////////////////////////////////// // Final step: Prints the Gridlets when simulation is over // also prints the routing table r1.printRoutingTable(); r2.printRoutingTable(); GridletList glList = null; for (i = 0; i < userList.size(); i++) { obj = (NetUser) userList.get(i); glList = obj.getGridletList(); printGridletList(glList, obj.get_name(), false); } System.out.println("\nFinish network example ..."); } catch (Exception e) { e.printStackTrace(); System.out.println("Unwanted errors happen"); } }
7
protected Icon getIcon() { java.net.URL url = getClass().getResource("/ICON/state_collapse.gif"); return new ImageIcon(url); }
0
public Channel getChannel() { if (name.equals(Server.get().getButler().getName())) { return null; } synchronized (channels) { return channels.get(channels.size() - 1); } }
1
@Override public void run(int interfaceId, int componentId) { if (stage == -1) { sendEntityDialogue(SEND_1_TEXT_CHAT, new String[] { player.getDisplayName(), "I'm hoping this is worth the time Reaper." }, IS_PLAYER, player.getIndex(), 12379); stage = 1; } else if (stage == 1) { sendEntityDialogue(SEND_4_TEXT_CHAT, new String[] { NPCDefinitions.getNPCDefinitions(npcId).name, "Oh please, Zenith is the Best.", "You can view our range of teleports and commands,", "by clicking the quest tab and clicking any button.", "Only donate to Laake/King Zenith!"}, IS_NPC, npcId, 12379); stage = 2; } else if (stage == 2) { sendEntityDialogue(SEND_4_TEXT_CHAT, new String[] { NPCDefinitions.getNPCDefinitions(npcId).name, "Rules of Zenith!", "Advertising other servers is a direct ban!", "Bug/glitch abuse will result with a talking to.", "Any offensive language will result in a possible mute. "}, IS_NPC, npcId, 12379); stage = 3; } else if (stage == 3) { sendEntityDialogue(SEND_4_TEXT_CHAT, new String[] { NPCDefinitions.getNPCDefinitions(npcId).name, "NO Duping what so ever!", "Begging for staff or pestering staff is forbiden.", "This could all result in your account getting ban.", ""}, IS_NPC, npcId, 12379); stage = 4; } else if (stage == 4) { sendEntityDialogue(SEND_4_TEXT_CHAT, new String[] { NPCDefinitions.getNPCDefinitions(npcId).name, "Please View the rest of the rules,", "and other infomation indebth on our forums.", "", ""}, IS_NPC, npcId, 12379); stage = 5; } else if (stage == 5) { // sendEntityDialogue(SEND_4_TEXT_CHAT, new String[] { NPCDefinitions.getNPCDefinitions(npcId).name, "", "We hope you enjoy your stay on Zenith!", ".", ""}, IS_NPC, npcId, 12379); stage = 6; } else if (stage == 6) { sendDialogue(SEND_2_OPTIONS, "Wana Play Zenith Now?", "Sure :D","Hell Yah"); if (componentId == 1) { Magic.sendNormalTeleportSpell(player, 0, 0, new WorldTile(2847, 10219, 0)); } else if (componentId == 2) { Magic.sendNormalTeleportSpell(player, 0, 0, new WorldTile(2847, 10219, 0)); } else end(); } }
9
protected static ArtifactType getArtifactTypeFromEntry(Entry entry) { // Take a look at what's in the JAXB artifact wrapper (if one exists). try { Artifact artifactWrapper = getArtifactWrapper(entry); if (artifactWrapper != null) { String hint = null; Element wrapperNode = getArtifactWrapperNode(entry); if (wrapperNode != null) { hint = getArtifactWrappedElementName(wrapperNode); } return ArtifactType.valueOf(artifactWrapper, hint); } } catch (JAXBException e) { } // Try the Category List<Category> categories = entry.getCategories(); for (Category cat : categories) { if (SrampAtomConstants.X_S_RAMP_TYPE.equals(cat.getScheme().toString())) { String atype = cat.getTerm(); ArtifactType artifactType = ArtifactType.valueOf(atype); if (artifactType.isExtendedType()) { artifactType = disambiguateExtendedType(entry, artifactType); } return artifactType; } } // Check the 'self' link Link link = entry.getLinkByRel("self"); //$NON-NLS-1$ if (link != null) { URI href = link.getHref(); String path = href.getPath(); String [] split = path.split("/"); //$NON-NLS-1$ String atype = split[split.length - 2]; //String amodel = split[split.length - 3]; ArtifactType artifactType = ArtifactType.valueOf(atype); if (artifactType.isExtendedType()) { artifactType = disambiguateExtendedType(entry, artifactType); } return artifactType; } // If all else fails! return ArtifactType.valueOf("Document"); //$NON-NLS-1$ }
8
public float getMaxSpeed() { return 0; }
0
public void testConstructorEx1_Type_int() throws Throwable { try { new Partial(null, 4); fail(); } catch (IllegalArgumentException ex) { assertMessageContains(ex, "must not be null"); } }
1
void copyUtf8ReadBuffer(int count) throws java.lang.Exception { int i = 0; int j = readBufferPos; int b1; boolean isSurrogate = false; while (i < count) { b1 = rawReadBuffer[i++]; isSurrogate = false; // Determine whether we are dealing // with a one-, two-, three-, or four- // byte sequence. if ((b1 & 0x80) == 0) { // 1-byte sequence: 000000000xxxxxxx = 0xxxxxxx readBuffer[j++] = (char) b1; } else if ((b1 & 0xe0) == 0xc0) { // 2-byte sequence: 00000yyyyyxxxxxx = 110yyyyy 10xxxxxx readBuffer[j++] = (char) (((b1 & 0x1f) << 6) | getNextUtf8Byte( i++, count)); } else if ((b1 & 0xf0) == 0xe0) { // 3-byte sequence: zzzzyyyyyyxxxxxx = 1110zzzz 10yyyyyy // 10xxxxxx readBuffer[j++] = (char) (((b1 & 0x0f) << 12) | (getNextUtf8Byte(i++, count) << 6) | getNextUtf8Byte( i++, count)); } else if ((b1 & 0xf8) == 0xf0) { // 4-byte sequence: 11101110wwwwzzzzyy + 110111yyyyxxxxxx // = 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx // (uuuuu = wwww + 1) isSurrogate = true; int b2 = getNextUtf8Byte(i++, count); int b3 = getNextUtf8Byte(i++, count); int b4 = getNextUtf8Byte(i++, count); readBuffer[j++] = (char) (0xd800 | ((((b1 & 0x07) << 2) | ((b2 & 0x30) >> 4) - 1) << 6) | ((b2 & 0x0f) << 2) | ((b3 & 0x30) >> 4)); readBuffer[j++] = (char) (0xdc | ((b3 & 0x0f) << 6) | b4); } else { // Otherwise, the 8th bit may not be set in UTF-8 encodingError("bad start for UTF-8 multi-byte sequence", b1, i); } if (readBuffer[j - 1] == '\r') { sawCR = true; } } // How many characters have we read? readBufferLength = j; }
6
public void printCosts(){ System.out.println("costs matrix for the traveling salesman problem:"); for(int i = 0;i<costs.length;i++){ for(int j = 0;j<costs[i].length;j++){ System.out.print(costs[i][j]+" "); } System.out.print("\n"); } }
2
private void createPaths() { if( path == null ) { path = new Path2D.Float(); closedPath = new Path2D.Float(); Iterator<Point> line = createLine().iterator(); if( line.hasNext() ) { Point previous = line.next(); List<Line2D> lines = new ArrayList<>(); List<Line2D> reverse = new ArrayList<>(); while( line.hasNext() ) { Point current = line.next(); lines.add( new Line2D.Float( previous.x, previous.y, current.x, current.y ) ); reverse.add( new Line2D.Float( current.x, current.y, previous.x, previous.y ) ); previous = current; } for( Line2D l : lines ) { path.append( l, true ); closedPath.append( l, true ); } for( int i = reverse.size() - 1; i >= 0; i-- ) { closedPath.append( reverse.get( i ), true ); } } } }
5
private boolean checkFields() { if(employeeName.getText().equals("")) { JOptionPane.showMessageDialog(this, "There is no such employee with that ID. Please enter a valid ID", "Incomplete Form", JOptionPane.WARNING_MESSAGE); return false; } if(employerName.getText().equals("")) { JOptionPane.showMessageDialog(this, "This Employee is not associated with any company currently. Please assign a " + "Field Placement in the Field Placements tab.", "Incomplete Form", JOptionPane.WARNING_MESSAGE); return false; } for(int i = 0; i < evaluationResults.length; i++) { if(evaluationResults[i].getText().equals("")) { JOptionPane.showMessageDialog(this, "Please fill out all boxes before submitting an evaluation.", "Incomplete Form", JOptionPane.WARNING_MESSAGE); return false; } } for(int i = 0; i < evaluationComments.length; i++) { if(evaluationComments[i].getText().equals("")) { JOptionPane.showMessageDialog(this, "Please fill out all boxes before submitting an evaluation.", "Incomplete Form", JOptionPane.WARNING_MESSAGE); return false; } } for(int i = 0; i < evaluationComments.length; i++) { if(evaluationComments[i].getText().length() > 256) { JOptionPane.showMessageDialog(this, "Some of your comments exceed 256 characters. Please change it so it is under 256" + " characters.", "Incomplete Form", JOptionPane.WARNING_MESSAGE); return false; } } return true; }
8
private static String cutString(final String string, final boolean deleteDelimiters, final String ending, final String... begining) throws Exception { if(!string.contains(ending)) throw new Exception(); boolean exists = false; for(final String temp : begining) if(string.contains(temp)) exists = true; if(!exists) throw new Exception(); int beginingIndex = 0; for(final String temp : begining) if((beginingIndex = string.indexOf(temp)) > -1) break; String result = string.substring(beginingIndex, string.indexOf(ending) + ending.length()); if(deleteDelimiters) { result = result.replace(ending, ""); for(final String temp : begining) result = result.replace(temp, ""); } return result; }
8
private void quitter() { System.out.println("Déconnexion du client..."); if (emetteur != null) { try { emetteur.close(); } catch (IOException e) { System.out.println("Problème de déconnexion."); } } System.out.println("Client déconnecté. Bye !"); }
2
public static void main(String[] args) { GraphDatabaseService graphDb = new GraphDatabaseFactory().newEmbeddedDatabase(Name.DB_PATH); Node refeNode = graphDb.getReferenceNode(); // 查找所有单位 logger.debug("==查找所有单位:"); Traverser orgTraverser = TraverserHelper.findAllOrg2(refeNode); for (Path orgPath : orgTraverser) { logger.debug(orgPath.endNode().getProperty(Name.NAME_KEY).toString()); } // 遍历某人的所有认识的人 logger.debug("==遍历某人的所有认识的人:"); Node xNode = graphDb.getNodeById(1); Traverser userTraverser = TraverserHelper.getFriends(xNode); for (Path userPath : userTraverser) { String chain = ""; for (Node node : userPath.nodes()) { chain += node.getProperty(Name.NAME_KEY).toString() + " → "; } logger.debug(userPath.endNode().getProperty(Name.NAME_KEY).toString() + "—深度为:" + userPath.length() + "(" + chain.substring(0, chain.length() - 2) + ")"); } // 两个人之间的最短路径 logger.debug("==两个人之间的最短路径(其实就是查找俩人之间的人脉关系):"); Node startNode = graphDb.getNodeById(8); Node endNode = graphDb.getNodeById(12); Path shortestPath = TraverserHelper.findShortestFriendPath(startNode, endNode); String chain = ""; for (Node node : shortestPath.nodes()) { chain += node.getProperty(Name.NAME_KEY).toString() + " → "; } logger.debug(chain.substring(0, chain.length() - 2)); // 查找所有有单位的人 logger.debug("==查找所有有单位的人:"); Traverser orgUserTraverser = TraverserHelper.findAllOrgUser(refeNode); for (Path orgUserPath : orgUserTraverser) { logger.debug(orgUserPath.endNode().getProperty(Name.NAME_KEY).toString()); } // 查找所有的BOSS logger.debug("==查找所有的BOSS:"); Traverser bossTraverser = TraverserHelper.findAllBoss(refeNode); for (Path bossPath : bossTraverser) { logger.debug(bossPath.endNode().getProperty(Name.NAME_KEY).toString()); } // 查找某人的所有同事 logger.debug("==查找某人的所有同事:"); Traverser colleagueTraverser = TraverserHelper.findColleague(xNode); for (Path colleaguePath : colleagueTraverser) { logger.debug(colleaguePath.endNode().getProperty(Name.NAME_KEY).toString()); } // 查找某人的BOSS logger.debug("==查找某人的BOSS:"); xNode = graphDb.getNodeById(3); logger.debug(xNode.getProperty(Name.NAME_KEY) + "的BOSS是"); Traverser myBossTraverser = TraverserHelper.findMyBoss(xNode); for (Path myBossPath : myBossTraverser) { logger.debug(myBossPath.endNode().getProperty(Name.NAME_KEY).toString()); } graphDb.shutdown(); }
8
private boolean inBounds(int x, int y) { return ( ((x >= 0) && (x < width)) && ((y >= 0) && (y < height)) ); }
3
public void onStop() throws JFException { // ストラテジーを停止した際に呼ばれます。 LOGGER.info("onStop"); printWriter.close(); }
0
public int getRatingId() { return ratingId; }
0
@Override public int[][] findMatching(DeviceGraph graph) { ObjectGraphBuilder ogb = new ObjectGraphBuilder(); HashSet<Requestor> requestors = ogb.buildObjectGraph(graph); int requestorCount = requestors.size(); HelperGroupFinder hgf = new HelperGroupFinder(); ArrayList<Requestor> matchedRequestors = new ArrayList<Requestor>(); int minDiff; Requestor bestCandidate; HelperGroup candidateHG; do { minDiff = Integer.MAX_VALUE; bestCandidate = null; candidateHG = null; for (Requestor r : requestors) { HelperGroup hg = hgf.findHelperGroup(r); if (hg.totalCapacity >= r.unitsOfWork && (hg.totalCapacity - r.unitsOfWork) < minDiff) { minDiff = hg.totalCapacity - r.unitsOfWork; bestCandidate = r; candidateHG = hg; } } if (bestCandidate != null) { bestCandidate.selectedHelperGroup = candidateHG; for (Helper h : candidateHG.helpers) { h.used = true; } matchedRequestors.add(bestCandidate); requestors.remove(bestCandidate); } } while (bestCandidate != null); int[][] requestorsAndGroups = new int[requestorCount][]; for (Requestor r : matchedRequestors) { requestorsAndGroups[r.i] = new int[r.selectedHelperGroup.helpers.size()]; for (int j = 0; j < requestorsAndGroups[r.i].length; j++) { requestorsAndGroups[r.i][j] = r.selectedHelperGroup.helpers.get(j).j; } } return requestorsAndGroups; }
8
public void uimsg(String msg, Object... args) { if(msg == "set") { synchronized(ui) { int i = 0, o = 0; while(i < equed.size()) { if(equed.get(i) != null) equed.get(i).unlink(); int res = (Integer)args[o++]; if(res >= 0) { int q = (Integer)args[o++]; Item ni = new Item(Coord.z, res, q, epoints.get(i), null); equed.set(i++, ni); if((o < args.length) && (args[o] instanceof String)) ni.settip((String)args[o++]); } else { equed.set(i++, null); } } } calcAC(); } else if(msg == "setres") { int i = (Integer)args[0]; Indir<Resource> res = ui.sess.getres((Integer)args[1]); equed.get(i).chres(res, (Integer)args[2]); calcAC(); } else if(msg == "settt") { int i = (Integer)args[0]; String tt = (String)args[1]; equed.get(i).settip(tt); calcAC(); } else if(msg == "ava") { avagob = (Integer)args[0]; } }
9
public void outputPMFile(PMFile file, File outputFile) { try { byte[] key = new BASE64Decoder().decodeBuffer(file.getPassword()); if (file.getNum() != null) { for (int i = 0; i < file.getNum().intValue(); i++) { File f = new File(Setting.DIRNAME_OF_SAVING_PMFILE + file.getName() + i + Setting.ENCODE_FILE_EXT); if (f != null && f.exists() && f.isFile()) { byte[] data = PMCipher.decrypt(this.readFile(f), key, Setting.CIPHER_SCHEME); boolean append = true; if (i == 0) { append = false; } this.writeFile(outputFile, data, append); } else { String message = "ファイル出力中にエラーが発生しました.\n" + "ファイル出力処理を中断します."; JOptionPane.showMessageDialog(this.mainFrame, message, "ファイル出力エラー", JOptionPane.ERROR_MESSAGE); break; } } } else { outputPMFileOld(file, outputFile); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (PMCipherException e) { e.printStackTrace(); } }
9
public AdjacencyList getMinBranching(Node root, AdjacencyList list) { AdjacencyList reverse = list.getReversedList(); // remove all edges entering the root if (reverse.getAdjacent(root) != null) { reverse.getAdjacent(root).clear(); } AdjacencyList outEdges = new AdjacencyList(); // for each node, select the edge entering it with smallest weight for (Node n : reverse.getSourceNodeSet()) { ArrayList<Edge> inEdges = reverse.getAdjacent(n); if (inEdges.size() == 0) { continue; } Edge min = inEdges.get(0); for (Edge e : inEdges) { if (e.weight < min.weight) { min = e; } } outEdges.addEdge(min.to, min.from, min.weight); } // detect cycles ArrayList<ArrayList<Node>> cycles = new ArrayList<ArrayList<Node>>(); cycle = new ArrayList<Node>(); getCycle(root, outEdges); cycles.add(cycle); for (Node n : outEdges.getSourceNodeSet()) { if (!n.visited) { cycle = new ArrayList<Node>(); getCycle(n, outEdges); cycles.add(cycle); } } // for each cycle formed, modify the path to merge it into another part of the graph AdjacencyList outEdgesReverse = outEdges.getReversedList(); for (int i=0; i<cycles.size(); i++) { if (cycles.get(i).contains(root)) { continue; } mergeCycles(cycles.get(i), list, reverse, outEdges, outEdgesReverse); } return outEdges; }
9
public void calculateInternals(double duration) { if (body[0] == null) swapBodies(); if (body[0] != null) { calculateContactBasis(); relativeContactPosition[0] = new Vector3d(contactPoint); relativeContactPosition[0].Substract(body[0].getPosition()); if (body[1] != null) { relativeContactPosition[1] = new Vector3d(contactPoint); relativeContactPosition[1].Substract(body[1].getPosition()); } contactVelocity = calculateLocalVelocity(0, duration); if (body[1] != null) { contactVelocity.Substract(calculateLocalVelocity(1, duration)); } calculateDesiredDeltaVelocity(duration); } }
4
@Override public boolean execute(MOB mob, List<String> commands, int metaFlags) throws java.io.IOException { final PlayerStats pstats=mob.playerStats(); if(pstats==null) return false; String channelName=commands.get(0).toUpperCase().trim().substring(2); commands.remove(0); int channelNum=-1; for(int c=0;c<CMLib.channels().getNumChannels();c++) { final ChannelsLibrary.CMChannel chan=CMLib.channels().getChannel(c); if(chan.name().equalsIgnoreCase(channelName)) { channelNum=c; channelName=chan.name(); } } if(channelNum<0) for(int c=0;c<CMLib.channels().getNumChannels();c++) { final ChannelsLibrary.CMChannel chan=CMLib.channels().getChannel(c); if(chan.name().toUpperCase().startsWith(channelName)) { channelNum=c; channelName=chan.name(); } } if((channelNum<0) ||(!CMLib.masking().maskCheck(CMLib.channels().getChannel(channelNum).mask(),mob,true))) { mob.tell(L("This channel is not available to you.")); return false; } if(!CMath.isSet(pstats.getChannelMask(),channelNum)) { pstats.setChannelMask(pstats.getChannelMask()|(1<<channelNum)); mob.tell(L("The @x1 channel has been turned off. Use `@x2` to turn it back on.",channelName,channelName.toUpperCase())); } else mob.tell(L("The @x1 channel is already off.",channelName)); return false; }
9
public BigDecimal mean_as_BigDecimal() { BigDecimal mean = BigDecimal.ZERO; switch (type) { case 1: double[] dd = this.getArray_as_double(); double meand = 0.0D; for (int i = 0; i < length; i++) meand += dd[i]; meand /= length; mean = new BigDecimal(meand); break; case 12: BigDecimal[] bd = this.getArray_as_BigDecimal(); for (int i = 0; i < length; i++) mean = mean.add(bd[i]); mean = mean.divide(new BigDecimal((double) length), BigDecimal.ROUND_HALF_UP); bd = null; break; case 14: throw new IllegalArgumentException("Complex cannot be converted to BigDecimal"); default: throw new IllegalArgumentException("This type number, " + type + ", should not be possible here!!!!"); } return mean; }
5
private static Boolean runStatement(String statement) { try { getConnection(); PreparedStatement st = con.prepareStatement(statement); st.executeUpdate(); return true; } catch (SQLException ex) { System.out.print(ex.getMessage()); return false; //something went wrong, will need to be handled! } }
1
public void makeNonVoid() { if (type != Type.tVoid) throw new jode.AssertError("already non void"); ClassInfo clazz = getClassInfo(); InnerClassInfo outer = getOuterClassInfo(clazz); if (outer != null && outer.name == null) { /* This is an anonymous class */ if (clazz.getInterfaces().length > 0) type = Type.tClass(clazz.getInterfaces()[0]); else type = Type.tClass(clazz.getSuperclass()); } else type = subExpressions[0].getType(); }
4
public static Comparator comparator() { if (Type.comparator != null) { return (Type.comparator); } Type.comparator = new Comparator() { public int compare(final Object o1, final Object o2) { // o1 < o2 : -1 // o1 == o2 : 0 // o1 > o2 : 1 if (!(o1 instanceof Type)) { throw new IllegalArgumentException(o1 + " not a Type"); } if (!(o2 instanceof Type)) { throw new IllegalArgumentException(o2 + " not a Type"); } final Type t1 = (Type) o1; final Type t2 = (Type) o2; final String d1 = t1.descriptor(); final String d2 = t2.descriptor(); return (d1.compareToIgnoreCase(d2)); } public boolean equals(final Object o) { if (o == this) { return (true); } else { return (false); } } }; return (Type.comparator); }
4
private void initialize(final int flags) { this.flags = flags; count = 0; count += ((flags&InputFlags.TA_IN_PRICE_OPEN)!=0) ? 1 : 0; count += ((flags&InputFlags.TA_IN_PRICE_HIGH)!=0) ? 1 : 0; count += ((flags&InputFlags.TA_IN_PRICE_LOW)!=0) ? 1 : 0; count += ((flags&InputFlags.TA_IN_PRICE_CLOSE)!=0) ? 1 : 0; count += ((flags&InputFlags.TA_IN_PRICE_VOLUME)!=0) ? 1 : 0; count += ((flags&InputFlags.TA_IN_PRICE_OPENINTEREST)!=0) ? 1 : 0; }
6
@Override public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel) { if((!mob.isInCombat())||(mob.rangeToTarget()<1)) { mob.tell(L("You really should be in ranged combat to cast this.")); return false; } for(int i=0;i<mob.location().numItems();i++) { final Item I=mob.location().getItem(i); if((I!=null)&&(I.fetchEffect(ID())!=null)) { mob.tell(L("There is already a wall of force here.")); return false; } } if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; final Physical target = mob.location(); final boolean success=proficiencyCheck(mob,0,auto); if(success) { final CMMsg msg = CMClass.getMsg(mob, target, this,verbalCastCode(mob,target,auto),auto?L("An impenetrable wall of force appears!"):L("^S<S-NAME> conjur(s) up a impenetrable wall of force!^?")); if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); final Item I=CMClass.getItem("GenItem"); I.setName(L("a wall of force")); I.setDisplayText(L("an impenetrable wall of force surrounds @x1",mob.name())); I.setDescription(L("It`s tough, that's for sure.")); I.setMaterial(RawMaterial.RESOURCE_NOTHING); CMLib.flags().setGettable(I,false); I.recoverPhyStats(); mob.location().addItem(I); theWall=I; beneficialAffect(mob,I,asLevel,10); } } else return beneficialWordsFizzle(mob,null,L("<S-NAME> incant(s), but the magic fizzles.")); // return whether it worked return success; }
9
HubNode ( Device dev, TreeNode parent ) throws IOException { super (dev, parent); hub = new Hub (dev); addr = dev.getAddress (); // Flat tree display: devices connect to root hub. if (isFlatTree) { if (hub.isRootHub ()) { Bus bus = dev.getBus (); children = new USBNode [127]; last = 0; for (int i = 1; i <= 127; i++) { Device d = bus.getDevice (i); if (d != null && d != dev) deviceAdded (d, null); } } else children = null; // Normal tree display: devices connect to their hubs. } else { children = new USBNode [hub.getNumPorts ()]; last = 0; for (int i = 1; i <= children.length; i++) { Device d = dev.getChild (i); if (d != null) deviceAdded (d, null); } } }
7
public String RetrieveActualPassword(String userName) throws SQLException{ String actualPassword=null; try{ databaseConnector=myConnector.getConnection(); stmnt=(Statement) databaseConnector.createStatement(); SQLQuery="SELECT password FROM familydoctor.login WHERE userName="+"'"+userName+"'"; dataSet=stmnt.executeQuery(SQLQuery); while(dataSet.next()){ actualPassword=dataSet.getString("password"); } } catch(SQLException e){ System.out.println(e.getMessage()); } finally{ if(stmnt!=null) stmnt.close(); if(databaseConnector!=null) databaseConnector.close(); } return actualPassword; }
4
public void render(GameContainer gc, Graphics g) throws SlickException{ if(dx == 0 && dy == 0){ if(facingRight) animation = idleRight; else animation = idleLeft; } animation.draw(x, y); g.setColor(Color.red); g.drawRect(x, y - 12, 16, 4); g.setColor(Color.green); g.drawRect(x, y - 12, 16 * health / maxHealth, 4); //String status = "health: " + health + "/" + maxHealth + " Spells: 1 - " + spells[0].getName() + ", 2 - " + spells[1].getName() + ", 3 - " + spells[2].getName(); }
3
private boolean containsExcludeToken(String agentString) { if (excludeList != null) { for (String exclude : excludeList) { if (agentString != null && agentString.toLowerCase().indexOf(exclude.toLowerCase()) != -1) return true; } } return false; }
4
public String getaddress() { return address; }
0
public static String getString(String urlString) throws MalformedURLException, IOException { URL url; InputStream is = null; BufferedReader br; String line; StringBuilder result = new StringBuilder(); try { url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection)url.openConnection(); connection.setRequestProperty("User-Agent", "User-Agent: Mozilla/5.0 (Windows NT 6.1; rv:27.0) Gecko/20100101 Firefox/27.0"); is = connection.getInputStream(); br = new BufferedReader(new InputStreamReader(is)); while ((line = br.readLine()) != null) { result.append(line); } } finally { if (is != null) { is.close(); } } return result.toString(); }
2
public void reset() { this.year=-1; this.month=-1; this.day=-1; this.hour=-1; this.minute=-1; this.second=-1; this.extraData=null; }
0
private String parsePrefix(final ByteArrayInputStream is) { final StringBuilder b = this.b; b.setLength(0); int ch; is.mark(0); ch = is.read(); if (ch != ':') { is.reset(); return ""; } ch = is.read(); while (ch != ' ' && ch != -1) { b.append((char) ch); if (ch == '!') { ch = is.read(); while (ch != ' ' && ch != -1) { b.append((char) ch); if (ch == '@') { ch = is.read(); while (ch != ' ' && ch != -1) { b.append((char) ch); ch = is.read(); } final String user = b.toString(); b.setLength(0); return user; } else { ch = is.read(); } } break; } else { ch = is.read(); } } b.setLength(0); return ""; }
9
public ClientListenerHandler(ServerSocket socket, String userName) { // TODO Auto-generated constructor stub socketListen = socket; run = true; myUserName = userName; }
0
protected boolean automatonActionPermissible(Component source) { if (!(getObject() instanceof Automaton)) return true; if (automaton.getInitialState() == null) { JOptionPane.showMessageDialog(source, "Simulation requires an automaton\n" + "with an initial state!", "No Initial State", JOptionPane.ERROR_MESSAGE); return false; } /* * If it is a Moore or Mealy machine, don't let it start if it has * nondeterministic states. */ if(automaton instanceof MealyMachine) { NondeterminismDetector d = NondeterminismDetectorFactory.getDetector(automaton); State[] nd = d.getNondeterministicStates(automaton); if(nd.length > 0) { JOptionPane.showMessageDialog(source, "Please remove nondeterminism for simulation.\n" + "Select menu item Test : Highlight Nondeterminism\nto see nondeterministic states.", "Nondeterministic states detected", JOptionPane.ERROR_MESSAGE); return false; } } /* * If it is a Turing machine, there are transitions from the final state, and that preference * hasn't been enabled, give a warning and return. */ else if (automaton instanceof TuringMachine && !Universe.curProfile.transitionsFromTuringFinalStateAllowed()) { TuringMachine turingMachine = (TuringMachine) automaton; Object[] finalStates = turingMachine.getFinalStates(); AutomatonDirectedGraph graph = new AutomatonDirectedGraph(turingMachine); for (int i=0; i<finalStates.length; i++) if (graph.fromDegree(finalStates[i], false) > 0) { JOptionPane.showMessageDialog(source, "There are transitions from final states. Please remove them or change " + "\nthe preference in the \"Preferences\" menu in the JFLAP main menu.", "Transitions From Final States", JOptionPane.ERROR_MESSAGE); return false; } } return true; }
8
static private boolean jj_3R_18() { Token xsp; xsp = jj_scanpos; if (jj_3_5()) { jj_scanpos = xsp; if (jj_3R_39()) { jj_scanpos = xsp; if (jj_3R_40()) { jj_scanpos = xsp; if (jj_3R_41()) { jj_scanpos = xsp; if (jj_3_6()) { jj_scanpos = xsp; if (jj_3R_42()) { jj_scanpos = xsp; if (jj_3R_43()) return true; } } } } } } return false; }
7
@Override public int getPages(int intRegsPerPag, ArrayList<FilterBean> hmFilter, HashMap<String, String> hmOrder) throws Exception { int pages; try { oMysql.conexion(enumTipoConexion); pages = oMysql.getPages("cliente", intRegsPerPag, hmFilter, hmOrder); oMysql.desconexion(); return pages; } catch (Exception e) { throw new Exception("ClienteDao.getPages: Error: " + e.getMessage()); } }
1
public Position GetPositionInFront(int Rotation) { Position Return = new Position(this.X, this.Y, this.Z); switch(Rotation) { case 0: Return.Y--; break; case 1: Return.X--; Return.Y--; break; case 2: Return.X++; break; case 3: Return.X--; Return.Y++; break; case 4: Return.Y++; break; case 5: Return.X++; Return.Y++; break; case 6: Return.X--; break; case 7: Return.X++; Return.Y--; break; } return Return; }
8
public void evaluate(Instance instance, Prediction prediction) { Label correct = instance.label(); Label predicted = prediction.winner(); if (correct.equals(predicted)) { if (correct.isPositive() && predicted.isPositive()) TP++; else if (!correct.isPositive() && !predicted.isPositive()) TN++; else if (correct.isPositive() && !predicted.isPositive()) FN++; else if (!correct.isPositive() && predicted.isPositive()) FP++; else { System.out.println("Completely confused: " + correct + "," + predicted); System.exit(1); } } else { System.out.println("Not a binary label: " + correct + "," + predicted); System.exit(1); } }
9
public void refuel(int fuel) { tank.refuel(fuel); if(!tank.isEmpty()) { setDead(false); } }
1
private boolean versionCheck(String title) { if (this.type != UpdateType.NO_VERSION_CHECK) { final String version = this.plugin.getDescription().getVersion().replace("dev", ""); if (title.split(" v").length == 2) { final String remoteVersion = title.split(" v")[1].split(" ")[0]; // Get the newest file's version number int remVer = -1, curVer = 0; try { remVer = this.calVer(remoteVersion); curVer = this.calVer(version); } catch (final NumberFormatException nfe) { remVer = -1; } if (this.hasTag(version) || version.equalsIgnoreCase(remoteVersion) || (curVer >= remVer)) { // We already have the latest version, or this build is tagged for no-update this.result = Updater.UpdateResult.NO_UPDATE; return false; } } else { // The file's name did not contain the string 'vVersion' final String authorInfo = this.plugin.getDescription().getAuthors().size() == 0 ? "" : " (" + this.plugin.getDescription().getAuthors().get(0) + ")"; this.plugin.getLogger().warning("The author of this plugin" + authorInfo + " has misconfigured their Auto Update system"); this.plugin.getLogger().warning("File versions should follow the format 'PluginName vVERSION'"); this.plugin.getLogger().warning("Please notify the author of this error."); this.result = Updater.UpdateResult.FAIL_NOVERSION; return false; } } return true; }
7
public void visitShiftExpr(final ShiftExpr expr) { if (expr.expr == from) { expr.expr = (Expr) to; ((Expr) to).setParent(expr); } else if (expr.bits == from) { expr.bits = (Expr) to; ((Expr) to).setParent(expr); } else { expr.visitChildren(this); } }
2
public void close() { System.out.println("tcp servers closed"); TCPServer tcpServer; for (int i = 0; i < tcpServers.size(); i++) { tcpServer = tcpServers.get(i); if (tcpServer != null) { tcpServer.keepRunning = false; } } shuttingDown = true; if (listenerSocket != null) { try { listenerSocket.close(); } catch (IOException e) { } } gameController.setNetworkMode(false); gameController.multiplayerMode = gameController.multiplayerMode.NONE; }
4
@Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final OutputCanDDeliveryOrderItemDetailPK other = (OutputCanDDeliveryOrderItemDetailPK) obj; if (!Objects.equals(this.szDocId, other.szDocId)) { return false; } if (!Objects.equals(this.shItemNumber, other.shItemNumber)) { return false; } if (!Objects.equals(this.szProductId, other.szProductId)) { return false; } return true; }
5
public synchronized Robot getRobot(String robot_name) { return robots.get(robot_name); }
0
public void update() throws IOException { checkTileMapCollision(); setPosition(xtemp, ytemp); if(dx == 0 && !hit) { setHit(); } animation.update(); if(hit && animation.hasPlayedOnce()) { remove = true; } }
4
public boolean isReturn() { switch (opcode) { case opc_areturn: case opc_ireturn: case opc_lreturn: case opc_freturn: case opc_dreturn: case opc_return: return true; default: return false; } }
6
public static void displayCalendar(int year) { Calendar cal = Calendar.getInstance(); cal.set(year, 0, 1); String[] months = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; String[] days = { "", "Su", "Mo", "Tu", "We", "Th", "Fr", "Sa" }; int x = 11 - months[0].length() / 2; for (int i = 0; i < 12; i++) { // display month for (int j = 0; j < x; j++) System.out.print(" "); System.out.println(months[i]); // display days for (String day : days) System.out.print(day + " "); System.out.println(); int index = 1; while (cal.get(Calendar.MONTH) == i) { if (cal.get(Calendar.DAY_OF_WEEK) == index) { System.out.printf("%3d", cal.get(Calendar.DAY_OF_MONTH)); index++; cal.add(Calendar.DAY_OF_MONTH, 1); } else { System.out.print(" "); index++; } if (index == 8) { System.out.println(); index = 1; } } System.out.println("\n"); } }
6
public static void main (String [] args ) { Piece p; Scanner keyboard = new Scanner (System.in); System.out.print ("Would you like to play with a Bishop, Knight or King? "); String answer = keyboard.nextLine (); if (answer.charAt(0) == 'b' || answer.charAt(0) == 'B') p = new Bishop(); else if (answer.charAt(1) == 'n' || answer.charAt(1) == 'N') p = new Knight(); else p = new King(); p.placeOnChessBoard (); System.out.println ("\n 1 2 3 4 5 6 7 8"); // number the columns for (int indexRow = 1; indexRow <= 8; indexRow++) { System.out.print (indexRow); // number the rows for (int indexColumn = 1; indexColumn <= 8; indexColumn++) { if (p.attackingThisLocation (indexRow, indexColumn)) System.out.print (" *"); else if ((indexColumn + indexRow) % 2 == 0) System.out.print (" b"); else System.out.print (" w"); } System.out.println (); } System.out.println (); }
8
public void compFinalResult() { do { iStage++; compAllocation(); if (compDistribution()) { /* deadline can not be satisfied */ if (!bDeadline) { System.out.println("THE DEADLINE CAN NOT BE SATISFIED!"); return; } else { System.out.println("\nNEW ROUND WITHOUT CHECKING:"); dEval = 1; } } else { compExecTime(); } // System.out.println("Evaluation Value =========="+dEval); } while (dEval > 0); // while (evaluateResults()); // System.out.println("==================Distribution====================="); for (int i = 0; i < iClass; i++) { // System.out.print("FinalDistribution[" + i + "] "); for (int j = 0; j < iSite; j++) { dmDist[i][j] = Math.round(dmDist[i][j]); // System.out.print(dmDistribution[i][j] + ","); } // System.out.println(); } // System.out.println("==================Allocation====================="); for (int i = 0; i < iClass; i++) { System.out.print("FinalAllocation[" + i + "] "); for (int j = 0; j < iSite; j++) { dmAlloc[i][j] = Math.round(dmAlloc[i][j]); // System.out.print(dmAllocation[i][j] + ","); } // System.out.println(); } // System.out.println("Stage = " + iStage); }
7
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(AddCliente.class .getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(AddCliente.class .getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(AddCliente.class .getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(AddCliente.class .getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the dialog */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { AddProduto dialog = new AddProduto(new javax.swing.JFrame(), true); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } }); }
6
public void setNote(Note note){ myNote = note; }
0
@Override protected Unmarshaller create() { try { return context.createUnmarshaller(); } catch (JAXBException e) { throw new XmlTransformationException("Failed to create jaxb unmarshaller", e); } }
1
public int patientsLengthRecursively() { if (this.isLast) { return 1; } else { return 1 + nextPatient.patientsLengthRecursively(); } }
1
@Basic @Column(name = "PCA_DESCRIPCION") public String getPcaDescripcion() { return pcaDescripcion; }
0
public Village getVillage() { return village; }
0
public String ObtenerImagen(String Ruta, String Nombre){ try { Mp3File mp3file = null; mp3file = new Mp3File(Ruta); if (mp3file != null && mp3file.hasId3v2Tag()) { ID3v2 id3v2Tag = mp3file.getId3v2Tag(); byte[] imageData = id3v2Tag.getAlbumImage(); BufferedImage img = ImageIO.read(new ByteArrayInputStream(imageData)); File miDir = new File ("."); try { Ruta = miDir.getCanonicalPath(); } catch(IOException e) { } //Guarsda la imagen extraida Ruta = Ruta+"/"+Nombre+".GIF"; ImageIO.write(img, "gif", new File(Ruta)); } } catch(NullPointerException e){ } catch (IOException | UnsupportedTagException | InvalidDataException ex) { Logger.getLogger(Extraer_imgen_allbum.class.getName()).log(Level.SEVERE, null, ex); } //Devuelve la ruta de la imagen para relacionarla con la cancion return Ruta; }
5
private String twoDigitString(int timeValue) { String result = Integer.toString(timeValue); if (result.length() == 1) { result = "0" + result; } return result; }
1