text
stringlengths
14
410k
label
int32
0
9
public String readText() throws IOException { StringBuilder builder = new StringBuilder(); String marker = getMarker(); if (mType == XMLNodeType.START_TAG) { next(); } do { if (mType == XMLNodeType.TEXT) { if (builder.length() > 0) { builder.append(' '); } builder.append(getText()); next(); } else if (mType == XMLNodeType.START_TAG) { skipTag(getName()); } } while (withinMarker(marker)); return builder.toString(); }
5
public void lookAt(String object, ArrayList<String> inv) { if (object.equalsIgnoreCase("floor")) { System.out.println("It is a cold and hard stone floor.\n"); } else if (object.equalsIgnoreCase("wall") || object.equalsIgnoreCase("walls")) { System.out.println("The walls are made of stone.\n"); } else if (object.equalsIgnoreCase("door")) { System.out.println("You see a large steel door. On closer inspection you can see that the words 'Speak, friend, and enter.' are etched \n" + "into the cold steel.\n"); } else if (object.equalsIgnoreCase("light")) { System.out.println("The soft light is coming from beneath the door.\n"); } else if (object.equalsIgnoreCase("telephone") || object.equalsIgnoreCase("phone")) { System.out.println("The phone is hanging by a hook on the wall. Its cord disappears between the stones, and it has no dial.\n"); } else if (object.equalsIgnoreCase("cord")) { System.out.println("The cord disappears into a crack in the stone wall.\n"); } else if (checkInv(object, inv)) { lookAtInv(object); } else { System.out.println("You want to look at what?\n"); } }
9
private void fixDeadReference(TreeNode referencedNode, TreeNode node) { if (node.leftIsWire && node.leftChild == referencedNode) { node.leftChild = referencedNode.parent; } if (node.rightIsWire && node.rightChild == referencedNode) { node.rightChild = referencedNode.parent; } }
4
public void destroy(String id) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception { EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); Area area; try { area = em.getReference(Area.class, id); area.getAreidArea(); } catch (EntityNotFoundException enfe) { throw new NonexistentEntityException("The area with id " + id + " no longer exists.", enfe); } List<String> illegalOrphanMessages = null; Collection<Depto> deptoCollectionOrphanCheck = area.getDeptoCollection(); for (Depto deptoCollectionOrphanCheckDepto : deptoCollectionOrphanCheck) { if (illegalOrphanMessages == null) { illegalOrphanMessages = new ArrayList<String>(); } illegalOrphanMessages.add("This Area (" + area + ") cannot be destroyed since the Depto " + deptoCollectionOrphanCheckDepto + " in its deptoCollection field has a non-nullable areaareidArea field."); } if (illegalOrphanMessages != null) { throw new IllegalOrphanException(illegalOrphanMessages); } Sucursal sucursalSucursalidSucursal = area.getSucursalSucursalidSucursal(); if (sucursalSucursalidSucursal != null) { sucursalSucursalidSucursal.getAreaCollection().remove(area); sucursalSucursalidSucursal = em.merge(sucursalSucursalidSucursal); } em.remove(area); em.getTransaction().commit(); } catch (Exception ex) { try { em.getTransaction().rollback(); } catch (Exception re) { throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re); } throw ex; } finally { if (em != null) { em.close(); } } }
8
@Override public synchronized Object getNext() { Object obj = super.getNext(); if (fileOpen) { try { while (processLine()) {} if (!fileOpen) {theStream.close();} } catch (IOException ioe) { System.err.println("Could not close FileReader: " + "\n" + ioe); } } return obj; }
4
public void calcThisFATEntOffset(int N) { int FATOffset = 0; if (typeOfFileSystem.equalsIgnoreCase("FAT16")) { FATOffset = N * 2; } else if (typeOfFileSystem.equalsIgnoreCase("FAT32")) { FATOffset = N * 4; } thisFATSecNum = BPB_ReservedSecCnt + (FATOffset / BPB_BytsPerSec); thisFATEntOffset = FATOffset % BPB_BytsPerSec; }
2
public void checkComment() { // discard obsolete comments while inside methods or fields initializer (see bug 74369) // don't discard if the expression being worked on is an ObjectLiteral (see bug 322412 ) if (!(this.diet && this.dietInt == 0) && this.scanner.commentPtr >= 0 && !(expressionPtr >= 0 && expressionStack[expressionPtr] instanceof ObjectLiteral)) { flushCommentsDefinedPriorTo(this.endStatementPosition); } int lastComment = this.scanner.commentPtr; // if (this.modifiersSourceStart >= 0) { // // eliminate comments located after modifierSourceStart if positionned // while (lastComment >= 0 && this.scanner.commentStarts[lastComment] > this.modifiersSourceStart) lastComment--; // } if (lastComment >= 0) { // consider all remaining leading comments to be part of current declaration this.modifiersSourceStart = this.scanner.commentStarts[0]; // check deprecation in last comment if javadoc (can be followed by non-javadoc comments which are simply ignored) while (lastComment >= 0 && this.scanner.commentStops[lastComment] < 0) lastComment--; // non javadoc comment have negative end positions // if (lastComment >= 0 && this.javadocParser != null) { // int commentEnd = this.scanner.commentStops[lastComment] - 1; //stop is one over, // // do not report problem before last parsed comment while recovering code... // this.javadocParser.reportProblems = this.currentElement == null || commentEnd > this.lastJavadocEnd; // if (this.javadocParser.checkDeprecation(lastComment)) { // checkAndSetModifiers(ClassFileConstants.AccDeprecated); // } // this.javadoc = this.javadocParser.docComment; // null if check javadoc is not activated // if (currentElement == null) this.lastJavadocEnd = commentEnd; // } } }
8
@Override public int rectIntersection( double x, double y, double w, double h ) { if( x + w <= this.x || x >= this.x + this.w || y + h <= this.y || y >= this.y + this.h ) { return INCLUDES_NONE; } if( x >= this.x && y >= this.y && x + w <= this.x + this.w && y + h <= this.y + this.h ) { return INCLUDES_ALL; } return INCLUDES_SOME; }
8
public void testGetChronology_Object_Zone() throws Exception { GregorianCalendar cal = new GregorianCalendar(TimeZone.getTimeZone("Europe/Paris")); assertEquals(GJChronology.getInstance(MOSCOW), CalendarConverter.INSTANCE.getChronology(cal, MOSCOW)); cal = new GregorianCalendar(TimeZone.getTimeZone("Europe/Moscow")); assertEquals(GJChronology.getInstance(), CalendarConverter.INSTANCE.getChronology(cal, (DateTimeZone) null)); cal = new GregorianCalendar(TimeZone.getTimeZone("Europe/Moscow")); cal.setGregorianChange(new Date(0L)); assertEquals(GJChronology.getInstance(MOSCOW, 0L, 4), CalendarConverter.INSTANCE.getChronology(cal, MOSCOW)); cal = new GregorianCalendar(TimeZone.getTimeZone("Europe/Moscow")); cal.setGregorianChange(new Date(Long.MAX_VALUE)); assertEquals(JulianChronology.getInstance(PARIS), CalendarConverter.INSTANCE.getChronology(cal, PARIS)); cal = new GregorianCalendar(TimeZone.getTimeZone("Europe/Moscow")); cal.setGregorianChange(new Date(Long.MIN_VALUE)); assertEquals(GregorianChronology.getInstance(PARIS), CalendarConverter.INSTANCE.getChronology(cal, PARIS)); Calendar uc = new MockUnknownCalendar(TimeZone.getTimeZone("Europe/Moscow")); assertEquals(ISOChronology.getInstance(PARIS), CalendarConverter.INSTANCE.getChronology(uc, PARIS)); try { Calendar bc = (Calendar) Class.forName("sun.util.BuddhistCalendar").newInstance(); bc.setTimeZone(TimeZone.getTimeZone("Europe/Moscow")); assertEquals(BuddhistChronology.getInstance(PARIS), CalendarConverter.INSTANCE.getChronology(bc, PARIS)); } catch (ClassNotFoundException ex) { // ignore } }
1
private Error unpackError() throws MikrotikApiException { nextLine(); Error err = new Error(); if (hasNextLine()) { while (!line.startsWith("!")) { if (line.startsWith(".tag=")) { String parts[] = line.split("=", 2); if (parts.length == 2) { err.setTag(parts[1]); } } else if (line.startsWith("=message=")) { err.setMessage(line.split("=", 3)[2]); } if (hasNextLine()) { nextLine(); } else { line = null; break; } } } return err; }
6
public P039C() { Scanner sc = new Scanner(System.in); N = sc.nextInt(); segments = new Segment[N]; dp = new int[N][N]; r = new boolean[N][N]; prev = new int[N]; for (int[] row: dp) { Arrays.fill(row, -1); } for (int i = 0; i < N; i++) { int c = sc.nextInt(); int r = sc.nextInt(); segments[i] = new Segment(c-r, c+r, i+1); } Arrays.sort(segments); int minLeft = segments[0].left; int minIndex = 0; for (int i = 1; i < N; i++) { if (segments[i].left < minLeft) { minLeft = segments[i].left; minIndex = i; } } for (int i = N-1; i >= 0; i--) { int left = segments[i].left; int p = i-1; while (p >= 0 && segments[p].right > left) p--; prev[i] = p; } System.out.println(solve(minIndex, N-1)); build(minIndex, N-1); }
7
private IMessage adapterMessage(IMessage m) { ArrayList<Character> al=new ArrayList<Character>(); for(int i=0;i<m.taille();i++) { if(m.getChar(i)==CARACTERE_INTERDIT) { for(int j=0;j<SUBSTITUTION.length();j++) { al.add(SUBSTITUTION.charAt(j)); } } else { if(m.getChar(i)==Character.toUpperCase(CARACTERE_INTERDIT)) { for(int j=0;j<SUBSTITUTION.length();j++) { al.add(SUBSTITUTION.toUpperCase().charAt(j)); } } else { al.add(m.getChar(i)); } } } Character[] ch=new Character[al.size()]; for(int i=0;i<al.size();i++) { ch[i]=al.get(i); } return Fabrique.fabriquerMessage(ch); }
6
protected void load() { Scanner in = null; try { in = new Scanner(file); } catch(FileNotFoundException e) { e.printStackTrace(); System.exit(0); } if (vertices == null) { vertices = new ArrayList<Vertex>(); textures = new ArrayList<Texture>(); triangles = new ArrayList<Triangle>(); } while(in.hasNextLine()) { final Scanner line = new Scanner(in.nextLine()); if (!line.hasNext()) { continue; } final String command = line.next(); if ("v".equals(command)) { vertices.add(new Vertex( line.nextFloat(), line.nextFloat(), line.nextFloat() )); } if ("vt".equals(command)) { textures.add(new Texture( line.nextFloat(), line.nextFloat() )); } if ("f".equals(command)) { // triangulate faces as necessary: List<int[]> corners = new ArrayList<int[]>(); while(line.hasNext()) { String[] pair = line.next().split("/"); corners.add(new int[] { Integer.parseInt(pair[0]) - 1, Integer.parseInt(pair[1]) - 1 }); } for(int z = 1; z < corners.size()-1; z++) { triangles.add(new Triangle( new Vertex [] { vertices.get(corners.get(0) [0]), vertices.get(corners.get(z) [0]), vertices.get(corners.get(z+1)[0]) }, new Texture [] { textures.get(corners.get(0) [1]), textures.get(corners.get(z) [1]), textures.get(corners.get(z+1)[1]) } )); } } } center(); in.close(); System.out.format("loaded model '%s'%n", file); }
9
public PersonApplication(Person p) { Area =""; WorkPosition = new ArrayList<String>(); Satisfied = false; Person = p; title=""; Contract=""; namePer=""; MobilePer=""; emailPer=""; companyLab=""; posLab=""; nameLab=""; MobileLab=""; }
0
public Key delMin() { if (N == 0) throw new RuntimeException("Priority Queue Underflow"); Key min = heap[1]; heap[1] = heap[N]; // half exchange heap[N--] = null; sink(1); // resize if (N == heap.length / 4) heap = resize(heap, heap.length / 2); return min; }
2
public void backupDoc(String indexName) throws Exception{ File file = new File(configService.getBackupDataFilePath(indexName)); JsonFactory jfactory = new JsonFactory(); /*** write to file ***/ JsonGenerator jGenerator = jfactory.createGenerator(file, JsonEncoding.UTF8); long startTime = System.currentTimeMillis(); Client esClient = configService.getBackupClient(); SearchResponse searchResponse = esClient.prepareSearch(indexName) // 加上这个据说可以提高性能,但第一次却不返回结果 .setSearchType(SearchType.SCAN) // 实际返回的数量为5*index的主分片格式 .setSize(1000) // 这个游标维持多长时间 .setScroll(TimeValue.timeValueMinutes(10000)) .execute().actionGet(); if(searchResponse.getScrollId() != null){ // 第一次查询,只返回数量和一个scrollId long docCount = searchResponse.getHits().getTotalHits(); long fetchCount = 0; logger.info("{} documents count:{}" , indexName,docCount); if(docCount==0){ /** * 无数据 */ logger.info("{} no data",indexName); return ; } int failedCount=0; while (fetchCount < docCount && failedCount<3) { // 只要取不够,一直取 // 使用上次的scrollId继续访问 searchResponse = esClient .prepareSearchScroll(searchResponse.getScrollId()) .setScroll(TimeValue.timeValueMinutes(8)).execute() .actionGet(); if(searchResponse.getHits().hits().length==0){ failedCount++; } else { fetchCount += searchResponse.getHits().hits().length; for (SearchHit hit : searchResponse.getHits()) { jGenerator.writeStartObject(); String indexNm=hit.getIndex(); jGenerator.writeStringField(Tag.INDEX_NAME_TAG, indexNm); // String typeNm=hit.getType(); jGenerator.writeStringField(Tag.TYPE_NAME_TAG, typeNm); // String docId = hit.getId(); jGenerator.writeStringField(Tag.DOC_ID_TAG, docId); // String doc = hit.getSourceAsString(); jGenerator.writeStringField(Tag.SOURCE_TAG, doc); // jGenerator.writeEndObject(); jGenerator.writeRaw("\n"); } if (fetchCount % 1000 == 0) { logger.info("{} backup document count:{}",indexName,fetchCount); } } } jGenerator.flush(); jGenerator.close(); logger.info("{} backup count:{}" ,indexName,fetchCount); logger.debug("{} backup useTime:{}",indexName, (System.currentTimeMillis() - startTime)); } else { /** * 未获得scrollId * TODO */ } }
7
private JButton makeButton(String label, String iconName, ActionListener listener, String tooltip) { ImageIcon icon = new ImageIcon(getClass().getResource( "/ICON/web/" + iconName)); JButton button = new JButton(label, icon); button.addActionListener(listener); button.setToolTipText(tooltip); return button; }
0
@Override public boolean process( final Set<? extends TypeElement> annotations, final RoundEnvironment roundEnv) { if (annotations == null || annotations.isEmpty()) { return false; } // we need the actual TypeElement of the annotation, not just it's name final TypeElement annotation = typeElement(ANNOTATION_TYPE); // make sure we have the annotation type if (annotation == null) { // no go for processing return false; } // get all classes that have the annotation final Set<? extends Element> annotatedElements = roundEnv.getElementsAnnotatedWith(annotation); try { // we will need to gather the annotated classes that we are // going to write to the services registration file final Set<String> results = new HashSet<String>(annotatedElements.size()); for (final Element m : annotatedElements) { // we know @Route is a type annotation so casting to TypeElement final TypeElement el = (TypeElement) m; // check that the class is not abstract since we cant instantiate it if it is // and that its of the correct type for our fi.zakar.control.Router if (el.getModifiers().contains(Modifier.ABSTRACT) || !isAssignable(m.asType(), Handler.class)) { // wasn't proper annotation -> go for compilation failure processingEnv.getMessager().printMessage(Kind.ERROR, "@Route annotated classes must be non-abstract and of type " + Handler.class, m); } else { // we are good to go, gather it up in the results results.add(el.getQualifiedName().toString()); } } // write the services to file registerControls(results); } catch (final IOException ioe) { System.out.println("ERROR" + ioe.getMessage()); processingEnv.getMessager().printMessage( Kind.ERROR, "I/O Error during processing."); ioe.printStackTrace(); } return true; }
9
public BValue parseBValue() { Token next = tk.next(); BValue ret; switch(next.getType()) { case Token.TRUE: ret = new Bool(true); break; case Token.FALSE: ret = new Bool(false); break; case Token.VAR: ret = new Variable("v" + Integer.toString(((VarToken) next).getIndex())); case Token.NOT: tk.next(); //LBracket BValue operand = parseBValue(); tk.next(); //RBracket ret = new BooleanOp(BooleanOpType.NOT, operand); break; case Token.LESS: { tk.next(); //LParen NValue n1 = parseNValue(); tk.next(); //Comma NValue n2 = parseNValue(); tk.next(); //RParen ret = new ArithmeticRel(ArithmeticRelType.LESS, n1, n2); break; } case Token.EQUAL: { tk.next(); //LParen NValue n1 = parseNValue(); tk.next(); //Comma NValue n2 = parseNValue(); tk.next(); //RParen ret = new ArithmeticRel(ArithmeticRelType.EQUAL, n1, n2); break; } case Token.GREATER: { tk.next(); //LParen NValue n1 = parseNValue(); tk.next(); //Comma NValue n2 = parseNValue(); tk.next(); //RParen ret = new ArithmeticRel(ArithmeticRelType.GREATER, n1, n2); break; } default: ret = null; } if(tk.peek().getType() == Token.AND) { tk.next();//discard the and return new BooleanOp(BooleanOpType.AND, ret, parseBValue()); } else if(tk.peek().getType() == Token.OR){ tk.next();//discard the or return new BooleanOp(BooleanOpType.OR, ret, parseBValue()); } else return ret; }
9
private boolean jj_2_42(int xla) { jj_la = xla; jj_lastpos = jj_scanpos = token; try { return !jj_3_42(); } catch(LookaheadSuccess ls) { return true; } finally { jj_save(41, xla); } }
1
public synchronized void move(Entity e, int x, int y){ int id = e.id; int w = e.width; int h = e.height; for(int cx = 0; cx < w; cx++) for(int cy = 0; cy < h; cy++){ int cxex = cx + (int) e.x; int cyey = cy + (int) e.y; int cxx = cx + x; int cyy = cy + y; world[cxex][cyey].remove(id); if(world[cxex][cyey].isEmpty()) world[cxex][cyey] = null; if(world[cxx][cyy] == null) world[cxx][cyy] = new GridLocation(); world[cxx][cyy].add(id); if(canMove(walker, cxex, cyey)) walkable[cxex][cyey] = 1; if(canMove(navigator, cxex, cyey)) navigable[cxex][cyey] = 1; if(!canMove(walker, cxx, cyy)) walkable[cxx][cyy] = 0; if(!canMove(navigator, cxx, cyy)) navigable[cxx][cyy] = 0; } }
8
public List<TravelTrip> findAll(){ CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<TravelTrip> criteria = cb.createQuery(TravelTrip.class); Root<TravelTrip> travelTrip = criteria.from(TravelTrip.class); criteria.select(travelTrip).orderBy(cb.asc(travelTrip.get("country"))); return em.createQuery(criteria).getResultList(); }
0
public void saveFile(String filename) { try { List<String> sections_list = new ArrayList<String>(); for (String key : map.keySet()) { String section = key.split("\\.")[0]; if (!sections_list.contains(section)) sections_list.add(section); } PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(filename), "UTF-8")); for (String sect : sections_list) { writer.write("[" + sect + "]\n"); for (String key : map.keySet()) { String[] keys = key.split("\\."); if (sect.equals(keys[0])) { writer.write(keys[1] + "=" + map.get(key) + '\n'); } } } writer.close(); } catch (Exception e) { // TODO Auto-generated catch block System.out.println("Error while saving ini file: " + filename); } }
6
public static GenericNode findeBestWay(GenericNode start) { @SuppressWarnings("Convert2Diamond") HashMap<GenericEdge, GenericNode> log; log = new HashMap<GenericEdge, GenericNode>(); GenericNode res = null, other, current = start; current.setDistance(0); PriorityQueue queue = new PriorityQueue(new ComparatorDistance()); while (res == null) { for (GenericEdge edge : (List<GenericEdge>) current.getEdges()) { edge.setAttribute((int) current.getDistance()); queue.push(new Element(edge)); log.put(edge, current); } if(queue.size() == 0) return current; GenericEdge temp = (GenericEdge) queue.pop().getValue(); while ((other = temp.getOther(current)) == null) { current = log.get(temp); } if (other.getDistance() > (current.getDistance() + temp.getAttribute().getValue())) { if (other.isActif() == false) { other.setDistance(temp.getAttribute().getValue() + current.getDistance()); other.previous = current; } } current.getEdges().remove(temp); current = temp.getOther(current); current.getEdges().remove(temp); if (current.getValue().equals("Sortie")) { res = current; } } return res; }
7
public int bonusGain(Territoire t) { List<Peuple> lstTmp = t.getPrisesDuTerritoire(Partie.getInstance().getTourEnCours()); Iterator<Peuple> it = lstTmp.iterator(); while( it.hasNext() ){ Peuple p = it.next(); if( p == this){ return 1; } } return 0; }
2
protected void consume(int cc) throws CompilationException { if ((cc<0) || (c!=cc)) { CompilationException exc= new CompilationException(c==-1?1:3,new Character((char)c)); exc.col=column; if (c==-1) exc.col--; throw exc; }; read(); };
4
public double inputToDouble() { double inputValue = 0; while (true) { try { inputValue = Double.valueOf(this.in.next().trim()); break; } catch (NumberFormatException e) { System.out.println("That wasn't a double value"); this.in.nextLine(); } catch (InputMismatchException e) { System.out.println("That wasn't a double value"); this.in.nextLine(); } } return inputValue; }
3
public static void executeDualGb(Gameboy gbL, Gameboy gbR, int[] movesL, int[] movesR) { // finish unfinished frames if (!gbL.onFrameBoundaries) gbL.step(); if (!gbR.onFrameBoundaries) gbR.step(); System.out.println("executeDualGb: initial steps " + gbL.stepCount + " - " + gbR.stepCount); // align to same frame while(gbL.stepCount < gbR.stepCount) gbL.step(); while(gbR.stepCount < gbL.stepCount) gbR.step(); // do and log moves for (int i = 0; i < Math.max(movesL.length, movesR.length); i++) { int moveL = i < movesL.length ? movesL[i] : 0; int moveR = i < movesR.length ? movesR[i] : 0; Gb.stepDual(gbL.gb, gbR.gb, moveL, moveR); if (Math.max(movesL.length, movesR.length) - i < 200) try { Thread.sleep(5); } catch (InterruptedException e) {} gbL.logInput(moveL); gbR.logInput(moveR); } // clean up gb state gbL.clearCache(); gbR.clearCache(); }
9
@Override public boolean isExistUrl(String url) { Statement stmt; ResultSet rs; ResultSet rsHistory; try { stmt = con.createStatement(); String query = "SELECT * FROM " + TABLE_NAME + " WHERE url = '" + url + "'"; rs = stmt.executeQuery(query); String query4History = "SELECT * FROM " + TABLE_HISTORY_NAME + " WHERE url = '" + url + "'"; rsHistory = stmt.executeQuery(query4History); while (rs.next() || rsHistory.next()) { return true; } rs.close(); rsHistory.close(); stmt.close(); } catch (SQLException e) { e.printStackTrace(); } return false; }
3
private boolean zzRefill() throws java.io.IOException { /* first: make room (if you can) */ if (zzStartRead > 0) { System.arraycopy(zzBuffer, zzStartRead, zzBuffer, 0, zzEndRead - zzStartRead); /* translate stored positions */ zzEndRead -= zzStartRead; zzCurrentPos -= zzStartRead; zzMarkedPos -= zzStartRead; zzStartRead = 0; } /* is the buffer big enough? */ if (zzCurrentPos >= zzBuffer.length) { /* if not: blow it up */ char newBuffer[] = new char[zzCurrentPos * 2]; System.arraycopy(zzBuffer, 0, newBuffer, 0, zzBuffer.length); zzBuffer = newBuffer; } /* finally: fill the buffer with new input */ int numRead = zzReader.read(zzBuffer, zzEndRead, zzBuffer.length - zzEndRead); if (numRead > 0) { zzEndRead += numRead; return false; } // unlikely but not impossible: read 0 characters, but not at end of // stream if (numRead == 0) { int c = zzReader.read(); if (c == -1) { return true; } else { zzBuffer[zzEndRead++] = (char) c; return false; } } // numRead < 0 return true; }
5
public Point toGate(Point current){ double ox = 0, oy = 0; Point gate = new Point(dimension/2, dimension/2); // if both the x and y of the piper are farther than 1 from the gate, change both // !finishround signifies that the piper is not ready to move towards the target yet if(Math.abs(gate.x - current.x) > 1 && Math.abs(gate.y - current.y) > 1 && !finishround){ double dist = PlayUtilities.distance(current, gate); assert dist > 0; ox = (gate.x - current.x) / dist * mpspeed; oy = (gate.y - current.y) / dist * mpspeed; } // if the x of the piper is farther than 1 from the gate, change x else if(Math.abs(gate.x - current.x) > 1 && !finishround){ double dist = PlayUtilities.distance(current, gate); assert dist > 0; ox = (gate.x - current.x) / dist * mpspeed; } // if the y of the piper is farther than 1 from the gate, change y else if(Math.abs(gate.y - current.y) > 1 && !finishround){ double dist = PlayUtilities.distance(current, gate); assert dist > 0; oy = (gate.y - current.y) / dist * mpspeed; } // now the piper is close to the gate, so it can move towards the target else if(Math.abs(target.x - current.x) > 1){ finishround = true; // change finishround to false to show that the piper has finished sweeping its region and can move to the left side double dist = PlayUtilities.distance(current, target); assert dist > 0; ox = (target.x - current.x) / dist * mpspeed; } Point next = new Point(current.x + ox, current.y + oy); return next; }
8
public boolean eatBloodMedicine(BloodMedicine bm){ if(this.isLive && bm.isLive() && this.getRect().intersects(bm.getRect())){ this.blood = 100; bm.setLive(false); return true; } return false; }
3
public void onPart(String chan, IRCUserInfo user, String msg) { String nick = user.getNick(); String username = user.getUsername(); String host = user.getHost(); if (msg.length() > 0) msg = " ("+ msg +")"; String line = "* Part: "+ nick +" ("+ username +"@"+ host +") parts "+ chan + msg; mainFrame.updateTab(chan, line); mainFrame.removeNick(chan, nick); if (nick.equals(conn.getNick())) mainFrame.closePanel(chan); }
2
@Override public void handle(HttpExchange exchange) throws IOException { Database db = new Database(); XStream xStream = new XStream(new DomDriver()); Search_Input input = (Search_Input) xStream.fromXML(exchange.getRequestBody()); String username = input.getUsername(); String password = input.getPassword(); ArrayList<Integer> fields = input.getFieldIDs(); ArrayList<String> searchValues = input.getSearchValues(); db.startTransaction(); User user = db.getUsers().getUser(username); Search_Output output = null; if(user != null && user.getPassword().equals(password)){ for(int i = 0; i < fields.size(); i++){ if(db.getFields().getField(fields.get(i)) == null){ exchange.sendResponseHeaders(404, 0); db.endTransaction(false); System.out.println("incorrect fieldID"); return; } } ArrayList<Value> result = new ArrayList<Value>(); for(int i = 0; i < fields.size(); i++){ for(int j = 0; j < searchValues.size(); j++){ ArrayList<Value> values = db.getValues().getValues(fields.get(i), searchValues.get(j)); if(values.size() != 0){ result.addAll(values); } } } if(result.size() == 0){ exchange.sendResponseHeaders(404, 0); db.endTransaction(false); System.out.println("no value found"); return; } ArrayList<Image> images = new ArrayList<Image>(); for(int i = 0; i < result.size(); i++){ int imageID = result.get(i).getImageID(); Image image = db.getImages().getImage(imageID); images.add(image); } exchange.sendResponseHeaders(200, 0); output = new Search_Output(result,images); OutputStream os = exchange.getResponseBody(); xStream.toXML(output, os); os.close(); } else{ exchange.sendResponseHeaders(404, 0); System.out.println("incorrect user input"); } db.endTransaction(false); }
9
public int getArmForce() { return armForce; }
0
public IllegalOrphanException(List<String> messages) { super((messages != null && messages.size() > 0 ? messages.get(0) : null)); if (messages == null) { this.messages = new ArrayList<String>(); } else { this.messages = messages; } }
3
public int compareTo(Object tmp ) { int result; if (tmp instanceof Person) result = (firstTicks < ((Person)tmp).GetFirstTicks() ? -1 : (firstTicks == ((Person)tmp).GetFirstTicks() ? 0 : 1)); else if (tmp instanceof BlankEvent) result = (firstTicks < ((BlankEvent)tmp).GetFirstTick() ? -1 : (firstTicks == ((BlankEvent)tmp).GetFirstTick() ? 0 : 1)); else result = (firstTicks < ((Bus)tmp).GetFirstTicks() ? -1 : (firstTicks == ((Bus)tmp).GetFirstTicks() ? 0 : 1)); return result; }
8
public void renderTile(int xp, int yp, Tile tile){ xp -= xOffset; yp -= yOffset; for (int y=0; y < tile.sprite.SIZE; y++){ int ya = y + yp; //ya is absolute y value, yp is offset for (int x=0; x < tile.sprite.SIZE; x++){ int xa = x + xp; if (xa < 0 - tile.sprite.SIZE || xa >= width || ya < 0 || ya >= height) break; //if it's off the screen, don't render it if (xa < 0){ xa = 0; } pixels [xa + ya * width] = tile.sprite.pixels[x+y*tile.sprite.SIZE]; } } }
7
public void doLargeDelimitedWithPZMap() { try { final String mapping = ConsoleMenu.getString("Mapping ", LargeDelimitedWithPZMap.getDefaultMapping()); final String data = ConsoleMenu.getString("Data ", LargeDelimitedWithPZMap.getDefaultDataFile()); LargeDelimitedWithPZMap.call(mapping, data); } catch (final Exception e) { e.printStackTrace(); } }
1
public void setDireccion(String direccion) { this.direccion = direccion; }
0
private void checkProductions(int x,int y) { HashSet <String> tempSet=new HashSet <String>(); for (int i=0; i<myProductions.length; i++) { for (int k=x; k<y; k++) { String key1=x+","+k; String key2=(k+1)+","+y; for (String A : myMap.get(key1)) { for (String B : myMap.get(key2)) { String target=A+B; if (myProductions[i].getRHS().equals(target)) { HashSet <String> temp2Set=new HashSet <String>(); tempSet.add(myProductions[i].getLHS()); temp2Set.add("0"+A+"/"+key1); temp2Set.add("1"+B+"/"+key2); String tempKey=x+","+y+myProductions[i].getLHS(); if (myMap.get(tempKey)!=null) temp2Set.addAll(myMap.get(tempKey)); myMap.put(tempKey, temp2Set); } } } } } String key=x+","+y; myMap.put(key, tempSet); }
6
@Override public String toString() { StringBuilder imports = new StringBuilder(); importLines.add( importJavaLines ); importLines.add( importJavaxLines ); importLines.add( importExternalLines ); importLines.add( importComLines ); for ( List<String> lines : importLines ) { for ( String line : lines ) { imports.append( line ); } if ( !lines.isEmpty() ) { imports.append( "\n" ); } } return imports.toString(); }
3
public boolean changeMixer(String mixerName) { Mixer mx=null; try { //stop current line this.line.stop(); this.line.close(); this.line.flush(); // Record this mixer change if (debugAudio==true) audioDebugDump("changeMixer() : mixerName="+mixerName); //set the new mixer and line mx=getMixer(mixerName); // If null we have a problem so return false if (mx==null) { if (debugAudio==true) audioDebugDump("changeMixer() : mx==null"); return false; } this.setMixer(mx); this.line=(TargetDataLine) getDataLineForMixer(); //restart if (openLine()==false) { if (debugAudio==true) audioDebugDump("changeMixer() : openLine()==false"); return false; } this.line.start(); } catch (Exception e) { // Record the exception errorMsg="changeMixer() : "+e.getMessage(); // then if a mixer has been obtained then display some information about it if (mx!=null) { Mixer.Info mInfo=mx.getMixerInfo(); errorMsg=errorMsg+"\nMixer Name : "+mInfo.getName()+"\nMixer Description : "+mInfo.getDescription(); } audioDebugDump(errorMsg); return false; } return true; }
7
public void saveDatabase() { try { File directory = new File(getDataFolder() + File.separator + "anvils"); if (!directory.exists()) directory.mkdirs(); for (File file : directory.listFiles()) { file.delete(); } for (int i = 0; i < anvils.size(); i++) { Location loc = (Location) anvils.keySet().toArray()[i]; double x = loc.getBlockX(); double y = loc.getBlockY(); double z = loc.getBlockZ(); String world = loc.getWorld().getUID().toString(); Writer out = new OutputStreamWriter(new FileOutputStream( new File(getDataFolder() + File.separator + "anvils", x + ";" + y + ";" + z + ";" + world + ".dat")), "UTF-8"); Inventory inv = (anvils.get(anvils.keySet().toArray()[i])); for (int j = 0; j <= 8; j++) { if (inv.getItem(j) != null) { ItemStack is = inv.getItem(j); ItemMeta meta = is.getItemMeta(); out.write(is.getType().name() + ":" + is.getAmount() + ":" + is.getDurability() + ":" + meta.getDisplayName() + ";" + "\n"); } else { out.write("AIR" + ":" + "0" + ":" + "0" + ":" + "null" + ";" + "\n"); } } out.flush(); out.close(); } } catch (Exception e) { log(e); } }
6
public static LogicObject findSelectionKeyWithEquivalents(Cons pattern) { { Cons candidatekeys = pattern.rest.rest; { Keyword testValue000 = ((Keyword)(pattern.value)); if ((testValue000 == Logic.KWD_DEPENDENTS) || (testValue000 == Logic.KWD_ISA)) { } else if (testValue000 == Logic.KWD_RELATION) { candidatekeys = candidatekeys.rest; } else if ((testValue000 == Logic.KWD_CONTEXT_PROPOSITIONS) || (testValue000 == Logic.KWD_CONTEXT_INSTANCES)) { candidatekeys = candidatekeys.rest; } else { { OutputStringStream stream000 = OutputStringStream.newOutputStringStream(); stream000.nativeStream.print("get-selection-key-equivalents: Can't yet handle pattern `" + pattern + "'"); throw ((StellaException)(StellaException.newStellaException(stream000.theStringReader()).fillInStackTrace())); } } } { Stella_Object key = null; Cons iter000 = candidatekeys; for (;!(iter000 == Stella.NIL); iter000 = iter000.rest) { key = iter000.value; if (Surrogate.subtypeOfP(Stella_Object.safePrimaryType(key), Logic.SGT_LOGIC_LOGIC_OBJECT)) { { LogicObject key000 = ((LogicObject)(key)); if (!(key000.variableValueInverse() == Stella.NIL)) { return (key000); } } } else { } } } return (null); } }
8
@Override public String toString() { return "Message["+source+"->"+dest+" seqNum:"+seqNum+" duplicate:"+duplicate+" kind:"+kind+" data:"+data+" TimeStamp:" + this.timeStamp + "]"; }
0
public void close() { try{ if(connection!=null && !connection.isClosed()) { connection.close(); connection=null; } }catch(SQLException ex) { ex.printStackTrace(); } }
3
static boolean inside(int r, int c) { return r >= 0 && r <= n && c >= 0 && c <= n - r; }
3
private boolean aggregate(char entryCharacter, char exitCharacter, boolean prefix) { if (c != entryCharacter) return false; nextCharacter(); skipWhiteSpace(); if (c == exitCharacter) { nextCharacter(); return true; } for(;;) { if (prefix) { int start = col; if (!string()) return error("string", start); skipWhiteSpace(); if (c != ':') return error("colon", col); nextCharacter(); skipWhiteSpace(); } if (value()) { skipWhiteSpace(); if (c == ',') { nextCharacter(); } else if (c == exitCharacter) { break; } else { return error("comma or " + exitCharacter, col); } } else { return error("value", col); } skipWhiteSpace(); } nextCharacter(); return true; }
9
public static void main(String args[]) throws FileNotFoundException { try { t = PdfUtilities.chooseFolder(); if (t != null) { ArrayList<File> files = PdfUtilities.getPaths(new File(t), new ArrayList<File>()); if (files == null) return; String extension; PdfReader reader; try { for (int i = 0; i < files.size(); i++) // prints out only files and not the subdirectories as // well if (!files.get(i).isDirectory()) { System.out.println(files.get(i).getCanonicalPath()); extension = Files.probeContentType(files.get(i) .toPath()); if (extension.equals("application/pdf")) { System.out.println(files.get(i)); try { reader = new PdfReader(files.get(i) .toString()); if (!reader.isEncrypted()) { repairWithItext(reader, files.get(i) .getName()); } } catch (Exception e) { System.out.println(e); } } } } catch (IOException e) { e.printStackTrace(); } } } catch (FileNotFoundException e) { } }
9
public void keyPressed(KeyEvent evt) { if (evt.getKeyCode() == keys[UP]) { this.direction = DIR_UP; } else if (evt.getKeyCode() == keys[DOWN]) { this.direction = DIR_DOWN; } else if (evt.getKeyCode() == keys[LEFT]) { this.direction = DIR_LEFT; } else if (evt.getKeyCode() == keys[RIGHT]) { this.direction = DIR_RIGHT; } else if (evt.getKeyCode() == keys[BOMB]) { dropBomb = true; } }
5
@Override protected String getModel() { return "Volvo XC90"; }
0
public int getArrowProjectileGfxId(int weaponId, int arrowId) { if (arrowId == 884) { return 11; } else if (arrowId == 886) { return 12; } else if (arrowId == 888) { return 13; } else if (arrowId == 890) { return 14; } else if (arrowId == 892) return 15; else if (arrowId == 11212) return 1120; else if (weaponId == 20171) return 1066; return 10;// bronze default }
7
private String getString(int next) throws IOException { StringBuilder str = new StringBuilder(); str.append((char) next); while (!isQuote((next = getChar()))) { // TODO: Properly read escape sequences str.append((char) next); } str.append((char) next); return str.toString(); }
1
public static void main(String[] args){ Scanner in = new Scanner(System.in); int n=in.nextInt(); int[] a = new int[n+1]; for(int i=0;i<n;i++){ a[i+1]=in.nextInt(); } int t = in.nextInt(); int[] d = new int[n+1]; int[] swap = new int[n+1]; int cnt = 0; for(int i=1;i<=n;i++){ if(a[i]==i){ d[i]=0; swap[i]=0; } else if(a[a[i]]==i){ cnt++; d[i]=2; d[a[i]]=2; swap[i]=a[i]; swap[a[i]]=i; } else { cnt++; d[i]=1; swap[i]=-1; } } int index = 1; while(cnt<t){ Point i = null; if(cnt<t-1){ // i = nextDouble(index); } if(cnt>=t-1 || i.x < 0){ // i = nextSingle(index); } } }
8
@Override public Customer readCustomer(int customerID) { if (doc == null) return null; Element currRoot = doc.getRootElement(); Element parrentCusto = currRoot.getChild("customers"); List<Element> listCustos = parrentCusto.getChildren(); for (Element customer : listCustos) { int newCustomerID = Integer.parseInt(customer .getChild("customerID").getText()); if (newCustomerID == customerID) { String name = customer.getChild("name").getText(); String surename = customer.getChild("surename").getText(); String address = customer.getChild("address").getText(); Customer cus = new Customer(name, surename, newCustomerID, address); return cus; } } return null; }
3
public int getSupplierCode() { return getValue().getSuppliercode(); }
0
public void woodcuttingComplex(int screen) { if (screen == 1) { clearMenu(); menuLine("1", "Normal Tree", 1511, 0); menuLine("1", "Achey Tree", 2862, 1); menuLine("10", "Light Jungle", 6281, 2); menuLine("15", "Oak Tree", 1521, 3); menuLine("20", "Medium Jungle", 6283, 4); menuLine("30", "Willow Tree", 1519, 5); menuLine("35", "Dense Jungle", 6285, 6); menuLine("35", "Teak Tree", 6333, 7); menuLine("45", "Maple Tree", 1517, 8); menuLine("45", "Hollow Tree", 3239, 9); menuLine("50", "Mahogany Tree", 6332, 10); menuLine("60", "Yew Tree", 1515, 11); menuLine("75", "Magic Tree", 1513, 12); optionTab("Woodcutting", "Trees", "Trees", "Hatchets", "Canoes", "Milestones", "", "", "", "", "", "", "", "", ""); } else if (screen == 2) { clearMenu(); menuLine("1", "Bronze Axe", 1351, 0); menuLine("1", "Iron Axe", 1349, 1); menuLine("6", "Steel Axe", 1353, 2); menuLine("6", "Black Axe", 1361, 3); menuLine("21", "Mithril Axe", 1355, 4); menuLine("31", "Adamant Axe", 1357, 5); menuLine("41", "Rune Axe", 1359, 6); menuLine("61", "Dragon Axe", 6739, 7); optionTab("Woodcutting", "Hatchets", "Trees", "Hatchets", "Canoes", "Milestones", "", "", "", "", "", "", "", "", ""); } else if (screen == 3) { clearMenu(); menuLine("12", "Log Canoe", 7414, 0); menuLine("27", "Dugout Canoe", 7414, 1); menuLine("42", "Stable Dugout Canoe", 7414, 2); menuLine("57", "Waka Canoe", 7414, 3); optionTab("Woodcutting", "Canoes", "Trees", "Hatchets", "Canoes", "Milestones", "", "", "", "", "", "", "", "", ""); } else if (screen == 4) { clearMenu(); menuLine("99", "Skill Mastery", c.getItems().skillcapes[c.playerWoodcutting][0], 0); optionTab("Woodcutting", "Milestones", "Trees", "Hatchets", "Canoes", "Milestones", "", "", "", "", "", "", "", "", ""); } }
4
private void draw() { double size = getWidth() < getHeight() ? getWidth() : getHeight(); canvas.setWidth(size); canvas.setHeight(size); ctx.clearRect(0, 0, size, size); if (isFrameVisible()) { //frame Paint frame = new LinearGradient(0.14 * size, 0.14 * size, 0.84 * size, 0.84 * size, false, CycleMethod.NO_CYCLE, new Stop(0.0, Color.rgb(20, 20, 20, 0.65)), new Stop(0.15, Color.rgb(20, 20, 20, 0.65)), new Stop(0.26, Color.rgb(41, 41, 41, 0.65)), new Stop(0.26, Color.rgb(41, 41, 41, 0.64)), new Stop(0.85, Color.rgb(200, 200, 200, 0.41)), new Stop(1.0, Color.rgb(200, 200, 200, 0.35))); ctx.setFill(frame); ctx.fillOval(0, 0, size, size); } InnerShadow innerShadow = new InnerShadow(BlurType.TWO_PASS_BOX, Color.rgb(0, 0, 0, 0.65), 0.07 * size, 0, 0, 0); if (isOn()) { //on ctx.save(); Paint on = new LinearGradient(0.25 * size, 0.25 * size, 0.74 * size, 0.74 * size, false, CycleMethod.NO_CYCLE, new Stop(0.0, ledColor.get().deriveColor(0d, 1d, 0.77, 1d)), new Stop(0.49, ledColor.get().deriveColor(0d, 1d, 0.5, 1d)), new Stop(1.0, ledColor.get())); innerShadow.setInput(new DropShadow(BlurType.TWO_PASS_BOX, ledColor.get(), 0.36 * size, 0, 0, 0)); ctx.setEffect(innerShadow); ctx.setFill(on); ctx.fillOval(0.14 * size, 0.14 * size, 0.72 * size, 0.72 * size); ctx.restore(); } else { // off ctx.save(); Paint off = new LinearGradient(0.25 * size, 0.25 * size, 0.74 * size, 0.74 * size, false, CycleMethod.NO_CYCLE, new Stop(0.0, ledColor.get().deriveColor(0d, 1d, 0.20, 1d)), new Stop(0.49, ledColor.get().deriveColor(0d, 1d, 0.13, 1d)), new Stop(1.0, ledColor.get().deriveColor(0d, 1d, 0.2, 1d))); ctx.setEffect(innerShadow); ctx.setFill(off); ctx.fillOval(0.14 * size, 0.14 * size, 0.72 * size, 0.72 * size); ctx.restore(); } //highlight Paint highlight = new RadialGradient(0, 0, 0.3 * size, 0.3 * size, 0.29 * size, false, CycleMethod.NO_CYCLE, new Stop(0.0, Color.WHITE), new Stop(1.0, Color.TRANSPARENT)); ctx.setFill(highlight); ctx.fillOval(0.21 * size, 0.21 * size, 0.58 * size, 0.58 * size); }
3
public static Card getHighestCard(Card card1, Card card2) { return (card1.getRank().getValue() > card2.getRank().getValue()) ? card1 : ((card1.getRank().getValue() < card2.getRank().getValue()) ? card2 : null); }
2
public boolean validarUsr(String nick, String psw){ //System.out.println(nick); //System.out.println(psw); getLista g = new getLista(); ListaClientes = g.getListaCliente(); for(int i = 0;i<ListaClientes.size();i++){ // System.out.println(ListaClientes.get(i).getNombre()); //System.out.println(ListaClientes.get(i).getContraseña()); if(ListaClientes.get(i).getNick().equals(nick)){ if(ListaClientes.get(i).getContraseña().equals(psw)){ return true; } } } getLista p = new getLista(); ListaProveedores = p.getListaProveedor(); for(int j=0; j<ListaProveedores.size();j++){ //System.out.println(ListaProveedores.get(j).getNombre()); if(ListaProveedores.get(j).getNick().equals(nick)){ //System.out.println(nick); //System.out.println(psw); if(ListaProveedores.get(j).getContraseña().equals(psw)){ return true; } } } return false; }
6
private void buildReport(ParseNode current, int indent, StringBuilder b) { while(current != null) { if(current.Terminal == null) { for(int i = 0; i < indent; i++) b.append(" "); // 2 spaces b.append(current.ProductionRule.toString()); b.append('\n'); // Children buildReport(current.FirstChild, indent + 1, b); } // Siblings current = current.Sibling; } }
3
@Override public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) { //System.out.println("getScrollableBlockIncrement"); switch(orientation) { case SwingConstants.VERTICAL: return visibleRect.height; case SwingConstants.HORIZONTAL: return visibleRect.width; default: throw new IllegalArgumentException("Invalid orientation: " + orientation); } }
2
@Override public void quit() { quitProgram(); }
0
public void updateDisplay() { if(userValues !=null && systemValues !=null) { for(int row = 0; row < systemValues.length; row++) { for(int col = 0; col < systemValues[row].length; col++) { systemValues[row][col] = userValues[row][col]; } } super.repaint(); } }
4
public double getDecimal(){ return (double)numerator / (double)denominator; }
0
public int etsiTasonNumero(ArrayList<String> rivit) { int tasonNumero = 0; for (String string : rivit) { if(string.startsWith("Taso: ")) { tasonNumero = Integer.parseInt(string.substring(6)); } } return tasonNumero; }
2
public Meeting getMeeting(int id) { Meeting returner = null; for (int i = 0; i < meetingList.size(); i++) { if (meetingList.get(i).getID() == id) { returner = meetingList.get(i); } } return returner; }
2
public void scrollCellToView(JTable table, int rowIndex, int vColIndex) { if (!(table.getParent() instanceof JViewport)) { return; } JViewport viewport = (JViewport) table.getParent(); Rectangle rect = table.getCellRect(rowIndex, vColIndex, true); Rectangle viewRect = viewport.getViewRect(); int x = viewRect.x; int y = viewRect.y; if (rect.x >= viewRect.x && rect.x <= (viewRect.x + viewRect.width - rect.width)){ } else if (rect.x < viewRect.x){ x = rect.x; } else if (rect.x > (viewRect.x + viewRect.width - rect.width)) { x = rect.x - viewRect.width + rect.width; } if (rect.y >= viewRect.y && rect.y <= (viewRect.y + viewRect.height - rect.height)){ } else if (rect.y < viewRect.y){ y = rect.y; } else if (rect.y > (viewRect.y + viewRect.height - rect.height)){ y = rect.y - viewRect.height + rect.height; } viewport.setViewPosition(new Point(x,y)); }
9
public final synchronized void sendRawLine(String line) { if (isConnected()) { System.out.println("Sending Raw Line: " + line); _inputThread.sendRawLine(line); } }
1
private void deSelectAllOtherSoundEffects(String key, String filename) { logger.logDebug("ENTERED deSelectAllOtherSoundEffects key = " + key + ", filename = " + filename); logger.logDebug(" key = " + key); logger.logDebug(" filename = " + filename); logger.logDebug(" listOfSoundFiles.size = " + listOfSoundFiles.size()); for (SoundFile sf : listOfSoundFiles) { if (sf == null) { logger.logDebug(" CURRENT sf IS NULL (can't happen), skipping"); continue; } logger.logDebug(" sf.newFilename = " + sf.newFilename); logger.logDebug(" sf.description = " + sf.description + "\n"); if (!filename.equals(sf.newFilename)) { if (key.equals(SoundFileController.SHOW_CURTAIN_SOUND_FILENAME)) { sf.isCurrentShowCurtainSound = false; } else if (key.equals(SoundFileController.REFILL_CURTAIN_SOUND_FILENAME)) { sf.isCurrentRefillCurtainSound = false; } else if (key.equals(SoundFileController.QUIT_CURTAIN_SOUND_FILENAME)) { sf.isCurrentQuitCurtainSound = false; } } } // AJA just added this.fireTableDataChanged(); }
6
private static boolean isLocationInScreenBounds(Point location) { GraphicsDevice[] graphicsDevices = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices(); for (int j = 0; j < graphicsDevices.length; j++) { if (graphicsDevices[j].getDefaultConfiguration().getBounds().contains(location)) { return true; } } return false; }
2
@Test public void twoCompCircular1() throws Exception { try { C1 c = new C1(); fail(); } catch (RuntimeException E) { assertTrue(E.getMessage().contains("src == dest")); } }
1
public final synchronized boolean isConnected() { return _inputThread != null && _inputThread.isConnected(); }
1
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPlayerItemHeld(PlayerItemHeldEvent event) { try { if((event.getPlayer().hasPermission("arctica.use")) && (!event.getPlayer().hasPermission("arctica.immune"))) { ItemStack newItem; newItem = event.getPlayer().getInventory().getItem(event.getNewSlot()); if ((null != newItem) && (newItem.getTypeId() == 50)) // Check if held item is a torch. Is null if empty slot. { if((plugin.playerIsAffected(event.getPlayer())) && (!playersHoldingTorch.contains(event.getPlayer().getName()))) { //if(Arctica.debug){event.getPlayer().sendMessage(ChatColor.GREEN + "Fackel-Bonus EIN.");} playersHoldingTorch.add(event.getPlayer().getName()); } } else // Player with permission has no torch in hand, so delete him from the List if he's on it. { // This should always be done, even if the player is currently not affected, to prevent exploiting the mechanism // Through leaving the cold biome if(playersHoldingTorch.contains(event.getPlayer().getName())) { //if(Arctica.debug){event.getPlayer().sendMessage(ChatColor.GREEN + "Fackel-Bonus AUS.");} playersHoldingTorch.remove(event.getPlayer().getName()); } } } } catch(Exception ex) { // player is probably no longer online } }
8
@Override public void doLayout() { Insets insets = getInsets(); int x = insets.left + HMargin; int y = insets.top + VMargin; Dimension d = classNameText.getPreferredSize(); classNameText.setBounds(x + ClassNameOffset + ClassNameSpace, y, d.width, d.height); y += d.height + InterVMargin; if (visibilityListView != null) { d = visibilityListView.getPreferredSize(); visibilityListView.setBounds(x + ClassContentOffset, y, d.width, d.height); y += d.height + InterVMargin; } if (inheritedClassView != null) { d = inheritedClassView.getPreferredSize(); inheritedClassView.setBounds(x + ClassContentOffset, y, d.width, d.height); y += d.height + InterVMargin; } for (AxiomaticView axiomaticView : axiomaticViews) { d = axiomaticView.getPreferredSize(); axiomaticView.setBounds(x + ClassContentOffset, y, d.width, d.height); y += d.height + InterVMargin; } for (BasicTypeView basicTypeView : basicTypeViews) { d = basicTypeView.getPreferredSize(); basicTypeView.setBounds(x + ClassContentOffset, y, d.width, d.height); y += d.height + InterVMargin; } for (FreeTypeView freeTypeView : freeTypeViews) { d = freeTypeView.getPreferredSize(); freeTypeView.setBounds(x + ClassContentOffset, y, d.width, d.height); y += d.height + InterVMargin; } for (AbbreviationView abbreviationView : abbreviationViews) { d = abbreviationView.getPreferredSize(); abbreviationView.setBounds(x + ClassContentOffset, y, d.width, d.height); y += d.height + InterVMargin; } if (stateView != null) { d = stateView.getPreferredSize(); stateView.setBounds(x + ClassContentOffset, y, d.width, d.height); y += d.height + InterVMargin; } if (initialStateView != null) { d = initialStateView.getPreferredSize(); initialStateView.setBounds(x + ClassContentOffset, y, d.width, d.height); y += d.height + InterVMargin; } for (OperationView operationView : operationViews) { d = operationView.getPreferredSize(); operationView.setBounds(x + ClassContentOffset, y, d.width, d.height); y += d.height + InterVMargin; } }
9
public float getFloat(String key, float _default) { return containsKey(key) ? get(key).floatValue() : _default; }
1
@Override public void onDisable() { synchronized (updateChecker) { try { getLogger().info("Waiting for updater to complete"); updateChecker.join(); } catch (InterruptedException ex) { getLogger().log(Level.SEVERE, "Error while waiting for update check thread", ex); } } }
1
public void undo(IDTextField field) { // no active list if (list == null) return ; int otherID = field.getMyID() ; int index = 0 ; boolean notFound = true ; ListIterator iterator = list.listIterator() ; // search for undo's while (iterator.hasNext() && notFound) { UndoData data = (UndoData) iterator.next() ; // take the first undo for the component with id <otherID> if (data.id == otherID) { field.setText( data.text ); field.setDataChanged(true); notFound = false ; list.remove(index) ; } else index++ ; } }
4
public void calculScore(){ int score = 0; for (Town t : towns){ if(t.isTown()==true) score += 2; else score++; } if (hasLonguestRoad==true) score += 2; if (hasBiggestArmy==true) score += 2; score += bonusScore; this.score = score; if(score>=10) { EndGameFrame endGame = new EndGameFrame(name,bonusScore); } }
5
private Cliente get_Cliente (String codigo){ String detalle = ""; Cliente cli = new Cliente(); r_con.Connection(); try { String sql = ( "SELECT cli_codigo, cli_nombre, cli_apellido, cli_fecha_nac, cli_cuit, loc_descripcion, cli_direccion, cli_calle, cli_sit_frente_iva, sfi_descripcion " + "FROM clientes, localidades, situacion_frente_iva " + "WHERE (cli_codigo = "+codigo+") AND (cli_localidad = loc_id) AND (cli_sit_frente_iva = sfi_id)"); ResultSet res = r_con.Consultar(sql); while(res.next()){ cli.setCodigo_cliente(Integer.parseInt(res.getString(1))); cli.setNombre_cliente(res.getString(2)); cli.setApellido_cliente(res.getString(3)); String fechaAux=res.getString(4); if((fechaAux!=null)&&(!fechaAux.equals(""))) fechaAux = fecha.convertirBarras(res.getString(4)); else fechaAux=""; cli.setFecha_nacimiento_cliente(fechaAux); String cuil = res.getString(5); if((cuil!=null)&&(!cuil.equals(""))){ cli.setCuil_prefijo_cliente(cuil.substring(0,2)); cli.setCuil_dni_cliente(cuil.substring(2,cuil.length()-1)); cli.setCuil_digito_cliente(cuil.substring(cuil.length()-1,cuil.length())); } else{ cli.setCuil_prefijo_cliente(""); cli.setCuil_dni_cliente(""); cli.setCuil_digito_cliente(""); } cli.setLocalidad_cliente(res.getString(6)); cli.setCalle_cliente(res.getString(7)); cli.setNumero_calle_cliente(res.getString(8)); cli.setCodigo_situacion_IVA_cliente(Integer.parseInt(res.getString(9))); cli.setDescripcion_situacion_IVA_cliente(res.getString(10)); } res.close(); } catch (SQLException ex) { Logger.getLogger(IGUI_Facturar.class.getName()).log(Level.SEVERE, null, ex); } finally {r_con.cierraConexion();} return cli; }
6
public void accel(double aX, double aY, double aZ) { velX += aX; velY += aY; velZ += aZ; if (Math.abs(velX) > speed) { velX = (velX / Math.abs(velX)) * speed; } if (Math.abs(velY) > speed) { velY = (velY / Math.abs(velY)) * speed; } if (Math.abs(velZ) > speed) { velZ = (velZ / Math.abs(velZ)) * speed; } moveswitch = true; }
3
public void PerformBroadcast() { if(!responseServer.running) { gameList.clear(); UpdateGameList(); } responseServer.startServerBroadcast(); }
1
@Override public boolean createTable(String query) { Statement statement = null; try { this.connection = this.getConnection(); if (query.equals("") || query == null) { this.writeError("SQL query empty: createTable(" + query + ")", true); return false; } statement = this.connection.createStatement(); statement.execute(query); return true; } catch (SQLException e) { this.writeError(e.getMessage(), true); return false; } catch (Exception e) { this.writeError(e.getMessage(), true); return false; } }
4
public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); char[] s1 = br.readLine().toCharArray(); char[] s2 = br.readLine().toCharArray(); int len1 = s1.length; int len2 = s2.length; int max_all = Integer.MIN_VALUE; int[][] lcs = new int[len1][len2]; for (int i = 0; i < len1; i++) { for (int j = 0; j < len2; j++) { int curr = 0; int max = 0; if (s1[i] == s2[j]) { curr = 1; try { max = lcs[i - 1][j - 1]; } catch (Exception e) { } } else { int v1 = 0; int v2 = 0; try { v1 = lcs[i - 1][j]; } catch (Exception e) { } try { v2 = lcs[i][j - 1]; } catch (Exception e) { } max = v1 > v2 ? v1 : v2; } lcs[i][j] = curr + max; max_all = max_all > lcs[i][j] ? max_all : lcs[i][j]; } } System.out.println(max_all); }
8
private void configurePropertiesForObjectSchema(JsonNode rawProperties, ObjectSchema schema, URL schemaLocation) { if (rawProperties == null) { return; } for (Iterator<String> iterator = rawProperties.fieldNames(); iterator.hasNext();) { String fieldName = iterator.next(); Property property = new Property(); property.setName(fieldName); JsonNode nestedSchema = rawProperties.get(fieldName); property.setNestedSchema(parse(nestedSchema, schemaLocation)); JsonNode required = nestedSchema.get("required"); if (required != null) { property.setRequired(required.booleanValue()); } schema.getProperties().add(property); } }
3
private void test(Class<?> clazz, String methodName, int expectedParamsCount) throws Exception { InvocationChainRetriever retriever = new InvocationChainRetriever(); String className = clazz.getName(); InputStream in = this.getClass().getResourceAsStream("/" + className.replace('.', '/') + ".class"); ClassFile cf = new ClassFile(new DataInputStream(in)); for (Object m : cf.getMethods()) { MethodInfo minfo = (MethodInfo)m; CodeAttribute ca = minfo.getCodeAttribute(); if (!"test".equals(minfo.getName())) { continue; } CodeIterator ci = ca.iterator(); ConstPool pool = cf.getConstPool(); while(ci.hasNext()) { int index = ci.next(); int op = ci.byteAt(index); if (!retriever.isInvoke(op)) { continue; } if (!methodName.equals(InvocationChainRetriever.getMethodName(cf, ci, index, op))) { continue; } int methodAddress = ci.s16bitAt(index + 1); String methodRefType = pool.getMethodrefType(methodAddress); int paramCount = retriever.getMethodParamCount(methodRefType); Assert.assertEquals(expectedParamsCount, paramCount); return; } } Assert.fail("Method " + methodName + " is not found in samples class " + clazz); }
6
public static void method208(boolean flag, Model model) { int i = 0; int j = 5; if (flag) { return; } Interface.modelCache.clear(); if (model != null && j != 4) { Interface.modelCache.put(model, (j << 16) + i); } }
3
private void load() { for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { pixels[x + y * width] = sheet.pixels[(x + this.x) + (y + this.y) * sheet.width]; } } }
2
@Override public void loadImages() { if(hImgLdr == null){ hImgLdr = new HorseRaceImageLoader(); } GameObject background = gameObjects.get("BACKGROUND"); if(backgroundStand == null){ backgroundStand = new BufferedImage[1]; } backgroundStand[0] = hImgLdr.scaleBufferedImage(hImgLdr.loadBufferedImage(HorseRaceImageLoader.BACKGROUND), background.getSize()); background.addAnimation(animationStand, backgroundStand); if(backgroundStandOpen == null){ backgroundStandOpen = new BufferedImage[1]; } backgroundStandOpen[0] = hImgLdr.scaleBufferedImage(hImgLdr.loadBufferedImage(HorseRaceImageLoader.BACKGROUND_OPEN), background.getSize()); background.addAnimation(animationStandOpen, backgroundStandOpen); boolean firstRun = true; if(horseStand == null){ horseStand = new BufferedImage[1]; } if(horseMove == null){ horseMove = new BufferedImage[HorseRaceImageLoader.HORSE_MOVE.length]; } for (Team team : playmode.getTeams()) { for (User user : team.getUser()) { GameObject playerObject = gameObjects.get("PLAYER" + user.getID()); if(firstRun){ firstRun = false; horseStand[0] = (hImgLdr.scaleBufferedImage(hImgLdr.loadBufferedImage(HorseRaceImageLoader.HORSE_STAND), playerObject.getSize())); for(int i = 0; i < HorseRaceImageLoader.HORSE_MOVE.length; i++){ horseMove[i] = (hImgLdr.scaleBufferedImage(hImgLdr.loadBufferedImage(HorseRaceImageLoader.HORSE_MOVE[i]), playerObject.getSize())); } } playerObject.addAnimation(animationStand, horseStand); playerObject.addAnimation(animationMove, horseMove); } } offscreen = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB); offscreenGraphics = offscreen.getGraphics(); imagesLoaded = true; }
9
public boolean isJumpPressed(){ if(isXboxControllerAttached()){ if(xboxController.isAPressed()){ return true; } } if(jump.isPressed()){ return true; } return false; }
3
private boolean initialiseNextBlock() throws IOException { /* If we're already at the end of the stream, do nothing */ if (this.streamComplete) { return false; } /* If a block is complete, check the block CRC and integrate it into the stream CRC */ if (this.blockDecompressor != null) { int blockCRC = this.blockDecompressor.checkCRC(); this.streamCRC = ((this.streamCRC << 1) | (this.streamCRC >>> 31)) ^ blockCRC; } /* Read block-header or end-of-stream marker */ final int marker1 = this.bitInputStream.readBits (24); final int marker2 = this.bitInputStream.readBits (24); if (marker1 == BZip2Constants.BLOCK_HEADER_MARKER_1 && marker2 == BZip2Constants.BLOCK_HEADER_MARKER_2) { // Initialise a new block try { this.blockDecompressor = new BZip2BlockDecompressor (this.bitInputStream, this.streamBlockSize); } catch (IOException e) { // If the block could not be decoded, stop trying to read more data this.streamComplete = true; throw e; } return true; } else if (marker1 == BZip2Constants.STREAM_END_MARKER_1 && marker2 == BZip2Constants.STREAM_END_MARKER_2) { // Read and verify the end-of-stream CRC this.streamComplete = true; final int storedCombinedCRC = this.bitInputStream.readInteger(); if (storedCombinedCRC != this.streamCRC) { throw new BZip2Exception ("BZip2 stream CRC error"); } return false; } /* If what was read is not a valid block-header or end-of-stream marker, the stream is broken */ this.streamComplete = true; throw new BZip2Exception ("BZip2 stream format error"); }
8
public void setSize(int size) { this.size = size; }
0
public void lisaaEste(Este este) { esteet.add(este); }
0
public String getDuration() { String duration = "-"; if(segments != null) { long durationMinutes = 0; for(int i=0; i< segments.size(); i++) { Segment segment = (Segment) segments.elementAt(i); if(segment.getDuration() != null) { String[] currDuration = StringUtil.split(segment.getDuration(), ":"); if(currDuration.length == 2) { try { //parse hours durationMinutes += Integer.parseInt(currDuration[0])*60; //parse minutes durationMinutes += Integer.parseInt(currDuration[1]); } catch (NumberFormatException nfe) { logger.error(nfe, "Invalid duration: " + segment.getDuration()); } } else { logger.error("Invalid duration: " + segment.getDuration()); } } } if(durationMinutes>0) { duration = durationMinutes/60 + "h "; duration = duration + durationMinutes%60 + "m"; } } return duration; }
6
static String formatDouble(double x, int just, int width, int dec) { int sign = 1; if (x < 0) { sign = -1; x = -x; } double pow10 = 1; for (int i = 0; i < dec; i++) { pow10 *= 10; } double y = Math.round(pow10 * x) / pow10; String s = "" + y; int i = s.indexOf('.'); int l = s.length(); if (i < 0) { s = s + "."; } i = s.indexOf('.'); if (l - i - 1 < dec) { for (int j = l - i; j <= dec; j++) { s = s + "0"; } } else if (l - i - 1 > dec) { s = s.substring(0, i + dec + 1); } if (sign < 0) { s = "-" + s; } while (s.length() < width) { if (just < 0) { s = s + " "; } else { s = " " + s; } } return s; }
9
@Override public Class getColumnClass(int indiceColonne){ //System.out.println("ModeleListeLocations::getColumnClass()") ; switch(indiceColonne){ case 0 : return Integer.class ; case 1 : return String.class ; case 2 : return String.class ; case 3 : return String.class ; case 4 : return String.class ; case 5 : return String.class ; case 6 : return JButton.class ; case 7 : return JButton.class ; case 8 : return JButton.class ; default : return Object.class ; } }
9
public void visitSRStmt(final SRStmt stmt) { if (stmt.array == from) { stmt.array = (Expr) to; ((Expr) to).setParent(stmt); } else if (stmt.start == from) { stmt.start = (Expr) to; ((Expr) to).setParent(stmt); } else if (stmt.end == from) { stmt.end = (Expr) to; ((Expr) to).setParent(stmt); } else { stmt.visitChildren(this); } }
3
protected void recursiveBalance(TreeNode currentNode) { setBalance(currentNode); int balance = currentNode.balance; if (balance == -2) { if (height(currentNode.left.left) >= height(currentNode.left.right)) { currentNode = rotateRight(currentNode); } else { currentNode = doubleRotateLeftRight(currentNode); } } else if (balance == 2) { if (height(currentNode.right.right) >= height(currentNode.right.left)) { currentNode = rotateLeft(currentNode); } else { currentNode = doubleRotateRightLeft(currentNode); } } if (currentNode.parent != null) { recursiveBalance(currentNode.parent); } else { this.root = currentNode; } }
5
public void printObj () { //Suppression des oiseaux qui ont touche quelque chose synchronized(Fenetre._list_birds) { for(int i = 0; i < Fenetre._list_birds.size(); i++) { if (Fenetre._list_birds.get(i).isDestructed()) { Fenetre._list_birds.remove(i); if (Fenetre._list_birds.size() != 0) Fenetre._fenster.changeBird(Fenetre._list_birds.get(0)); } } } //Suppression des walkers qui ont touche quelque chose synchronized(Fenetre._list_walkers) { for(int i = 0; i < Fenetre._list_walkers.size(); i++) { if (Fenetre._list_walkers.get(i).isDestructed()) { Fenetre._list_walkers.remove(i); } } } //Suppression des oeufs qui ont touche quelque chose synchronized(Fenetre._list_egg) { for(int i = 0; i < Fenetre._list_egg.size(); i++) { if (Fenetre._list_egg.get(i).isDestructed()) { Fenetre._list_egg.remove(i); } } } Fenetre._fenster.repaint(); }
7