text
stringlengths
14
410k
label
int32
0
9
private boolean checkStartBuffer() { int a,count=0,o; // Check for 21 true bits in the first 44 bits for (a=0;a<44;a++) { if (startBuffer[a]==true) count++; } if (count!=21) return false; count=0; // Check the 70 bit session keys are almost the same for (a=0;a<70;a++) { if (startBuffer[a+44]!=startBuffer[a+44+70]) count++; } if (count>1) return false; // Check the session key contains at least 8 valid ITA3 characters count=0; for (a=44;a<(44+70);a=a+7) { o=extractIntFromStart(a); if (checkITA3Char(o)==true) count++; } if (count>=8) return true; else return false; }
9
private boolean hasRowWithNumber(int number) { for (Row row : rows) { if (row.getNumber() == number) { return true; } } return false; }
2
public void setPlayerTitle(Player p, String title, boolean save) throws UnknownTitleException { String confPath = "players." + p.getName(); if (title.equalsIgnoreCase("none")) { p.setDisplayName(p.getName()); if (save) { fastTitles.getConfig().set(confPath, null); } } else { String titleFormat = getTitle(title); if (titleFormat != null) { p.setDisplayName(formatString(colorize(titleFormat), p.getName())); if (save) { fastTitles.getConfig().set(confPath, title); } } else { throw new UnknownTitleException("That title doesn't exist"); } } }
4
public float GetDensity(String location){ float density = 0f; WAQuery query = engine.createQuery(); query.setInput(location+" population density"); try { WAQueryResult queryResult = engine.performQuery(query); if (queryResult.isError()) { } else if (!queryResult.isSuccess()) { } else { for (WAPod pod : queryResult.getPods()) { if (!pod.isError()) { if(pod.getTitle().equals("Result")){ for (WASubpod subpod : pod.getSubpods()) { for (Object element : subpod.getContents()) { if (element instanceof WAPlainText) { String s = (((WAPlainText) element).getText().substring(0,((WAPlainText) element).getText().indexOf(" "))); density = Float.parseFloat(s); } } } } } } } } catch (WAException e) { e.printStackTrace(); } return density; }
9
@Override public void update(int mouseX, int mouseY, boolean pressed) { super.update(mouseX, mouseY, pressed); if(this.btnResume.wasClicked()) Game.instance.setCurrentGui(null); if(this.btnNewGame.wasClicked()) { Game.instance.world = new World(); Game.instance.setCurrentGui(null); } if(this.btnControls.wasClicked()) Game.instance.setCurrentGui(new GuiControls(this, this.x, this.y, this.width, this.height)); if(this.btnInstruction.wasClicked()) Game.instance.setCurrentGui(new GuiInstruction(this, this.x, this.y, this.width, this.height)); if(this.btnCredit.wasClicked()) Game.instance.setCurrentGui(new GuiCredit(this, this.x, this.y, this.width, this.height)); }
5
public static void SS() throws IOException{ int timeblock = 5; BufferedReader r = new BufferedReader (new InputStreamReader(System.in)); while (timeblock > 0){ System.out.println("What would you like to do right now?"); if (timeblock >= 3) { System.out.println("1. Study"); System.out.println("2. Go workout at the Gym"); System.out.println("3. Play games at home"); System.out.println("4. Sleep (what you always do anyways)"); System.out.println("Damon would like to choose option: "); int choice = DamonTools.validInput(Integer.parseInt(r.readLine()), 4, 1); if (choice == 1){ System.out.println(""); DamonStats.Knowledge ++; System.out.println("Damon studied quite hard. He learned some new stuff."); } else if (choice == 2) DamonActions.Gym(); else if (choice == 3) { DamonActions.GAMING(); } else { System.out.println("Damon slept through the day. He did not get to do anything."); timeblock = 0; } timeblock -= 1; } else { System.out.println("1. Go workout at the Gym"); System.out.println("2. Play games at home"); System.out.println("3. Sleep (what you always do anyways)"); int choice = DamonTools.validInput(Integer.parseInt(r.readLine()), 3, 1); if (choice == 1) { DamonActions.Gym(); } else if (choice == 2) { DamonActions.GAMING(); } else { System.out.println("Damon slept through the day. He did not get to do anything."); timeblock = 0; } timeblock -= 1; } } }
7
@Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Tile other = (Tile) obj; if (this.x != other.x) { return false; } if (this.y != other.y) { return false; } return true; }
4
public static long getScaleFactorDecimal(final String scaleUnit) { if(scaleUnit == null) throw new IllegalArgumentException("Ihre Präfix-Angabe ist ungültig. " + scaleUnit); if(scaleUnit.length() == 0) return 1; switch(scaleUnit.toLowerCase().charAt(0)) { case 'h': return 100; case 'k': return 1000; case 'm': return 1000 * 1000; case 'g': return 1000 * 1000 * 1000; case 't': return (1000l * 1000l * 1000l * 1000l); case 'p': return (1000l * 1000l * 1000l * 1000l * 1000l); case 'e': return (1000l * 1000l * 1000l * 1000l * 1000l * 1000l); default: throw new IllegalScaleUnitException("Ihre Angabe ist keine gültige Einheit! " + scaleUnit); } }
9
public void move(int shipx, int shipy){ if(getxCoord() < shipx+30){ this.setImageIcon(finImage1R); setxCoord(getxCoord() + speed); } if(getxCoord() > shipx+30){ this.setImageIcon(finImage1); setxCoord(getxCoord() - speed); } if(getyCoord() < shipy+80){ setyCoord(getyCoord() + speed); } if(getyCoord() > shipy+80){ setyCoord(getyCoord() - speed); } }
4
public void setBlockLocation(SelectMode selectMode, Location location) { switch (selectMode) { case FirstBlock: { RegionManager manager = RegionManager.getInstance(); manager.addRegion(player.getUniqueId(), new Region()); getNewestRegion().setLocation(selectMode, location); } break; case SecondBlock: { RegionManager manager = RegionManager.getInstance(); getNewestRegion().setLocation(selectMode, location); } break; } }
2
public void findGames(ArrayList<Game> games) { String name; String path = "."; String fileName; File folder = new File(path); File[] listOfFiles = folder.listFiles(); for(int i = 0; i < listOfFiles.length; i++) { if(listOfFiles[i].isFile()) { fileName = listOfFiles[i].getName(); if(fileName.endsWith(".txt") || fileName.endsWith(".TXT")) { for(int j = 0; j<fileName.length(); j++) { if(fileName.charAt(j) == '.') { name = fileName.substring(0, j); Game game = new Game(name); games.add(game); System.out.println(games); } } } } } }
6
public static void main(String[] args) { Scanner in = new Scanner(System.in); double a, b, c; double i; String str; System.out.println("This program will sort from lowest to highest 3 numbers."); System.out.print("Please enter your first number: "); str = in.nextLine(); a = Double.parseDouble(str); System.out.print("Please enter your second number: "); str = in.nextLine(); b = Double.parseDouble(str); if(b < a){ i = a; a = b; b = i; } System.out.print("Please enter your third number: "); str = in.nextLine(); c = Double.parseDouble(str); if(c < a){ i = c; c = b; b = a; a = i; } else if(c < b){ i = c; c = b; b = i; } System.out.println(a); System.out.println(b); System.out.println(c); }
3
public String getEncoding() { if (internalIn2 == null) return null; return internalIn2.getEncoding(); }
1
public int numDecodings(String s) { if (s == null || s.length() == 0 || s.charAt(0) == '0') { return 0; } int[] number = new int[s.length() + 1]; number[0] = 1; number[1] = 1; int tmp; for (int i = 2; i <= s.length(); i++) { // 检查当前字符是不是'0' tmp = Integer.parseInt(s.substring(i - 1, i)); if (tmp != 0) { number[i] = number[i - 1]; } // 检查当前字符和前一个字符组合在一起是否在10-26之间 tmp = Integer.parseInt(s.substring(i - 2, i)); if (tmp >= 10 && tmp <= 26) { number[i] += number[i - 2]; } } return number[s.length()]; }
7
private static void startStatCollector(String host, int port, final Connector connector) { connector.setStatsOn(true); logger.fine("Starting stats collector: " + host + ":" + port); GangliaStat statCollector = new GangliaStat(host, port, 30, 60); statCollector.addMetric(new StatReporter("os_cs_keys_registered", "keys") { @Override public double getValue() { int length = CommunityDAO.get().getRegisteredKeys().length; logger.finest("Stats collector: reg users=" + length); return length; } }); statCollector.addMetric(new StatReporter("os_connections_opened", "Connections open") { public double getValue() { return connector.getConnectionsOpen(); }}); statCollector.addMetric(new StatReporter("os_connections", "Connections") { public double getValue() { return connector.getConnections(); }}); statCollector.addMetric(new StatReporter("os_requests", "Requests") { public double getValue() { return connector.getRequests(); }}); statCollector.addMetric(new StatReporter("os_connection_duration", "ms") { public double getValue() { double v = connector.getConnectionsDurationAve(); connector.statsReset(); return v; } }); statCollector.addMetric(new StatReporter("os_cs_users_online", "users") { @Override public double getValue() { /* * users are online for 2x the refresh limit + 60 seconds */ long online_limit = Long.parseLong(System.getProperty(Setting.REFRESH_INTERVAL.getKey())) * 60 * 1000 + 60 * 1000; int onlineUsers = 0; KeyRegistrationRecord[] registeredKeys = CommunityDAO.get().getRegisteredKeys(); for (KeyRegistrationRecord rec : registeredKeys) { if ((System.currentTimeMillis() - rec.getLastRefreshedDate().getTime()) < online_limit) { onlineUsers++; } } logger.finest("Stats collector: online users=" + onlineUsers); return onlineUsers; } }); statCollector.addMetric(new StatReporter("os_cs_ram_used", "Bytes") { @Override public double getValue() { Runtime runtime = Runtime.getRuntime(); // System.gc(); // System.gc(); long mem_used = runtime.totalMemory() - runtime.freeMemory(); logger.finest("Stats collector: mem used=" + mem_used); return mem_used; } }); }
2
private Object handleSubn(Object tos, String id, String ref) { if (tos instanceof Header && ref != null && ((Header)tos).getSubmissionRef() == null) { ((Header)tos).setSubmissionRef(ref); return new Object(); // placeholder } else if (tos instanceof Header && ref == null && ((Header)tos).getSubmission() == null) { Submission submission = new Submission(); ((Header)tos).setSubmission(submission); return submission; } else if (tos instanceof Gedcom && ((Gedcom)tos).getSubmission() == null) { Submission submission = new Submission(); if (id != null) { submission.setId(id); } ((Gedcom)tos).setSubmission(submission); return submission; } return null; }
9
private void addCadenaOperador(String string) { if (INICIO) { if (maxCaracteres()) { if (!ordenSecuencia()) { if (!string.isEmpty()) { if (cadenaCalculo.isEmpty()) { cadenaCalculo = string; } else { cadenaCalculo += " " + string; } jLabelCalculo.setText(cadenaCalculo); SECUENCIA++; } else { JOptionPane.showMessageDialog(this, "No se han iniciado valores", "No hay valores", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(this, "Tienes que colocar un número", "Falta número", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(this, "Haz llegado al tope de números", "Máximo de números", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(this, "Iniciar el juego", "Inicia", JOptionPane.ERROR_MESSAGE); } }
5
public HashMap<String,HashMap<String,String>> getFriendships(){ HashMap<String,HashMap<String,String>> friendships = new HashMap<String,HashMap<String,String>>(); HashMap<String,String> buddies = new HashMap<String,String>(); Statement st; ResultSet rs; String query; query = "SELECT * FROM friends"; try{ st = conn.createStatement(); rs = st.executeQuery(query); while (rs.next()){ buddies = new HashMap<String,String>(); buddies.put(rs.getString(2),rs.getString(3)); friendships.put(rs.getString(1),buddies); } }catch (SQLException e) { e.printStackTrace(); } return friendships; }
2
final int importBinary(XMLElement elem, int offs, ByteBuffer buf, String fieldName) throws XMLImportException { if (elem == null || elem.isNullValue()) { offs = buf.packI4(offs, -1); } else if (elem.isStringValue()) { String hexStr = elem.getStringValue(); int len = hexStr.length(); buf.extend(offs + 4 + len/2); Bytes.pack4(buf.arr, offs, len/2); offs += 4; for (int j = 0; j < len; j += 2) { buf.arr[offs++] = (byte)((getHexValue(hexStr.charAt(j)) << 4) | getHexValue(hexStr.charAt(j+1))); } } else { XMLElement ref = elem.getSibling("ref"); if (ref != null) { buf.extend(offs + 4); Bytes.pack4(buf.arr, offs, mapId(getIntAttribute(ref, "id"))); offs += 4; } else { XMLElement item = elem.getSibling("element"); int len = (item == null) ? 0 : item.getCounter(); buf.extend(offs + 4 + len); Bytes.pack4(buf.arr, offs, len); offs += 4; while (--len >= 0) { if (item.isIntValue()) { buf.arr[offs] = (byte)item.getIntValue(); } else if (item.isRealValue()) { buf.arr[offs] = (byte)item.getRealValue(); } else { throwException("Conversion for field " + fieldName + " is not possible"); } item = item.getNextSibling(); offs += 1; } } } return offs; }
9
public Layer getParentLayer() { return parentLayer; }
0
private boolean isBlocked(float x, float y) { boolean blocked = false; float tweakedX = x + 4; float tweakedY = y + 8 + mapY; int rowCount = genX / blockSize; int startY = (Math.round(mapY / blockSize))* rowCount + 1; int endY = (Math.round((mapY + screenHeight) / blockSize) - 1)* rowCount; if(startY < 0) startY = 0; if(endY > map.length) endY = map.length; if(tweakedX > screenWidth || tweakedX < 0) blocked = true; playerBoundingRect.setLocation(tweakedX,tweakedY); for(int i = startY; i < endY; i++){ if(playerBoundingRect.intersects(map[i])){ if(map[i].type != 0){ blocked = true; } } } return blocked; }
7
public void finishTag() throws TagParserException { // System.out.print("NT"+this.mLD()); TagNode container = this.containerStack.peek(); TagNode tag = this.temporaryTag; // Parse the Attributes if there are any. if(this.literalBuffer.length() > 0) { // Though before we do so,check if there is a '/' at the end of the literal-buffer. if(this.literalBuffer.charAt(this.literalBuffer.length()-1) == '/') { // There IS a '/' at the end of the buffer. Cut it away and add it to the typeName of the current Tag. tag.typeName += '/'; this.literalBuffer.setLength(this.literalBuffer.length()-1); } // Now parse the attributes tag.addAttributes(this.transformAttributes(this.literalBuffer.toString())); } // Determine the Tag-Type. tag.tagType = this.determineTagType(tag, container); // Depending on the Type of the Tag, we will either... // POP the current container from the containerStack, ignoring this Tag as 'end'-tag. But only if the current container has the same name! // PUSH this tag as an 'start'-tag onto the containerStack. // ADD this tag to the container as a 'single'-tag. // // By doing this, we can easily create a tag-tree while parsing, without doing multiple passes of the data. switch(tag.tagType) { case 0: // START-TAG container.addChild(tag); this.containerStack.push(tag); this.temporaryTag = null; break; case 1: // END-TAG this.containerStack.pop(); this.temporaryTag = null; break; case 2: // SINGLE-TAG container.addChild(tag); this.temporaryTag = null; break; // This should NOT happen. case -1: default: throw this.makeException("TagType unresolved or unknown: " + tag.tagType); } // Clear the literal-buffer to parse the next literal. this.literalBuffer.setLength(0); }
6
public MoveResult endOfMoveChecker(MoveResult battleResult) { MoveResult result = battleResult; boolean redCanMove = false; boolean blueCanMove = false; if (result.getStatus() == OK) //If someone has not already won { for (PieceLocationDescriptor piece: pieceHandler.getRedPieces()) { if (canMove(piece)) { redCanMove = true; break; } } for (PieceLocationDescriptor piece: pieceHandler.getBluePieces()) { if (canMove(piece)) { blueCanMove = true; break; } } if (!redCanMove && !blueCanMove) //Neither team can move, draw { result = new MoveResult(DRAW, result.getBattleWinner()); gameOver = true; } else if (!redCanMove) //Red can not move, blue wins { result = new MoveResult(BLUE_WINS, result.getBattleWinner()); gameOver = true; } else if (!blueCanMove) //Blue can not move, red wins { result = new MoveResult(RED_WINS, result.getBattleWinner()); gameOver = true; } } return result; }
9
private String checkIfInBounds(Point p) { int borderSize = 25; // right side if (p.x >= this.getWidth() - borderSize && p.x <= this.getWidth()) { // is in right side return "right"; } else if (p.x >= 0 && p.x <= borderSize) { // is in left side return "left"; } else if (p.y >= 0 && p.y <= 10) { // is in top side return "top"; } else if (p.y <= this.getHeight() && p.y >= this.getHeight() - borderSize) { // is in bottom side return "bottom"; } else { return null; } }
8
public char deleteItem() {//since previous is already in the Links, switching the code around allows for a Queue implementation fairly trivially char temp; if (stack) {//this is the stack implementation, which is the assignment if (isEmpty()) throw new EmptyStackException(); temp = (char) pointer.getDatum(); if (pointer.getNext() == pointer) { pointer = null; return temp; } pointer.getNext().setPrevious(pointer.getPrevious()); pointer.getPrevious().setNext(pointer.getNext()); pointer=pointer.getNext(); } if (queue) {//now with bonus optional queue implementation. if (isEmpty()) throw new EmptyStackException(); temp=(char)pointer.getPrevious().getDatum(); if (pointer.getPrevious()==pointer) { pointer=null; return temp; } pointer.setPrevious(pointer.getPrevious().getPrevious()); pointer.getPrevious().setNext(pointer); } return temp; }
6
public void mousePressed(MouseEvent e) { // click, moved from mouseClicked due // to problems with focus and stuff if ((e.getModifiers() & InputEvent.BUTTON1_MASK) != 0) { Point p = e.getPoint(); CPArtwork artwork = controller.getArtwork(); int layerIndex = getLayerNb(p); if (layerIndex >= 0 && layerIndex < artwork.getLayersNb()) { CPLayer layer = artwork.getLayer(layerIndex); if (p.x < eyeW) { artwork.setLayerVisibility(layerIndex, !layer.visible); } else { artwork.setActiveLayer(layerIndex); } } } if ((e.getModifiers() & InputEvent.BUTTON1_MASK) != 0) { Dimension d = getSize(); CPArtwork artwork = controller.getArtwork(); Object[] layers = artwork.getLayers(); int layerOver = (d.height - e.getPoint().y) / layerH; if (layerOver < layers.length) { layerDrag = true; layerDragY = e.getPoint().y; layerDragNb = layerOver; repaint(); } } }
6
public void stop(String sourcename) { if (sourcename == null || sourcename.equals("")) { errorMessage("Sourcename not specified in method 'stop'"); return; } if (midiSourcename(sourcename)) { midiChannel.stop(); } else { Source mySource = sourceMap.get(sourcename); if (mySource != null) mySource.stop(); } }
4
public void actionPerformed(ActionEvent ae) { if(ae.getSource() == bp.getExit()) { System.exit(0); } if(ae.getSource() == bp.getFight()) { } if(ae.getSource() == bp.getEndTurn()) { engine.endTurn(); System.out.println("Turn Ending ..."); ep.addText("\nCash on hand: " + engine.getTaxes()); } }
3
public static int getHeightItr(Node root){ //Write your code here if(root == null) { return 0; } int height = 0; Queue<Node> children = new LinkedList<Node>(); children.add(root); while(true) { int childCount = children.size(); if(childCount == 0) { break; } int count = 0; while(count < childCount) { Node temp = children.poll(); if(temp.left != null) { children.add(temp.left); } if(temp.right != null) { children.add(temp.right); } count++; } height++; } height--; return height; }
6
public static ArrayList<Rating> getTestSet(String file) { ArrayList<Rating> testset = new ArrayList<Rating>(); InputStream fis = null; BufferedReader br; try { fis = new FileInputStream(file); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } br = new BufferedReader(new InputStreamReader(fis, Charset.forName("UTF-8"))); try { String line; while ((line = br.readLine()) != null) { // Deal with the line String fields[] = line.split(","); Rating r = new Rating(); r.user = Long.parseLong(fields[0]); r.item = Long.parseLong(fields[1]); r.rating = Float.parseFloat(fields[2]); testset.add(r); } br.close(); fis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return testset; }
3
public static Account constructAccountObject(String username) { ResultSet result = accessAccount(username); Account account = null; try { result.next(); String uname = result.getNString(1); String pass = result.getNString(2); int employee_id = result.getInt(3); String employee_name = result.getNString(4); int type = result.getInt(5); String[] names = employee_name.split("\\s+"); String fname = names[0]; String lname = names[1]; Boolean blocked = result.getBoolean(6); if (type == 1) { account = new SystemAdmin(fname, lname, employee_id, uname, pass); } else if (type == 2) { account = new AcademicAdmin(fname, lname, employee_id, uname, pass); } else if (type == 3) { account = new AssistantAdmin(fname, lname, employee_id, uname, pass); } else if (type == 4) { account = new Instructor(fname, lname, employee_id, uname, pass); } else if (type == 5) { account = new TATM(fname, lname, employee_id, uname, pass); } else { account = new TATM(fname, lname, employee_id, uname, pass); System.out.println("There was an error with account type; " + "account type set to TA/TM"); } account.setBlocked(blocked); return account; } catch (SQLException ex) { System.out.println("SQL Exception occured, the state : " + ex.getSQLState() + "\nMessage: " + ex.getMessage()); } System.out.println("Returning a null account because something " + "failed while retrieving the account"); return account; }
6
private CalcState work(CalcState state) { CalcState bestState = state; for (int point2 = state.point1 + 1; point2 < conf.numPoints; point2++) { Point p2 = new Point(Main.xFromPoint(point2), Main.yFromPoint(point2)); StringBuilder s = new StringBuilder(); s.append(Main.now()); s.append(String.format("Worker %d ", workerNumber)); s.append(String.format("starting point (%9s,%9s) ", state.p1, p2)); s.append(String.format("of triangle %d", state.triangleNumber)); System.out.println(s); for (int point3 = point2 + 1; point3 < conf.numPoints; point3++) { Point p3 = new Point(Main.xFromPoint(point3), Main.yFromPoint(point3)); int det = (p2.y-p3.y) * (state.p1.x-p3.x) - (p3.x-p2.x) * (p3.y-state.p1.y); if (det == 0) { continue; } CalcState tempState = testPoints(state, p2, p3); if (tempState.bestDist < bestState.bestDist) { bestState = tempState; } } } if (bestState.bestDist < state.bestDist) { return bestState; } else { return new CalcState(null, Double.POSITIVE_INFINITY, state.triangleNumber, state.point1, state.p1, Double.POSITIVE_INFINITY, null); } }
5
private void testInstanceRange_X(int range) { ((TimeSeriesTranslate)m_Filter).setInstanceRange(range); Instances result = useFilter(); // Number of attributes and instances shouldn't change assertEquals(m_Instances.numAttributes(), result.numAttributes()); assertEquals(m_Instances.numInstances() - Math.abs(range), result.numInstances()); // Check conversion looks OK for (int i = 0; i < result.numInstances(); i++) { Instance in = m_Instances.instance(i - ((range > 0) ? 0 : range)); Instance out = result.instance(i); for (int j = 0; j < result.numAttributes(); j++) { if ((j != 1) && (j != 2)) { if (in.isMissing(j)) { assertTrue("Nonselected missing values should pass through", out.isMissing(j)); } else if (result.attribute(j).isString()) { assertEquals("Nonselected attributes shouldn't change. " + in + " --> " + out, m_Instances.attribute(j).value((int)in.value(j)), result.attribute(j).value((int)out.value(j))); } else { assertEquals("Nonselected attributes shouldn't change. " + in + " --> " + out, in.value(j), out.value(j), TOLERANCE); } } } } }
7
private void createTables(){ try{ con = DriverManager.getConnection(dbURL2); st = con.createStatement(); // for loop iterate over all elements in the array and create the tables for (String h : c){ String insert = "CREATE TABLE \"ME\"."+ h + "(CountryCode VARCHAR(5) NOT NULL, CurrencyName VARCHAR(50), Rate DECIMAL(10,5),\n" + "RetreiveDate TIMESTAMP, primary key (CountryCode))"; st.execute(insert); p++; } st.close(); con.close(); }catch(SQLException e){} }
2
public void move(int xa, int ya) { if (xa != 0 && ya != 0) { move(xa, 0); move(0, ya); return; } if (xa < 0) dir = 3; if (ya < 0) dir = 0; if (xa > 0) dir = 1; if (ya > 0) dir = 2; if (light(xa, ya, dir)) { xa /= 2; ya /= 2; } if (!collision(xa, ya)) { x += xa; y += ya; } }
8
public String pickUp(Room room) { if(room instanceof ItemRoom) { ItemRoom ir = (ItemRoom) room; boolean bool = true; for(int i = 0; i < 6 && bool; i++) { if(inv[i] == null) { inv[i] = ir.getItem(); this.lastSlotUsed = i; bool = false; return "You have picked up the " + inv[i].getName(); } if(i == 5)//it didnt find an empty slot { return "Your inventory is full. You cannot bear to carry a bigger burden."; } } } return "There is Nothing to Pick Up"; }
5
private static boolean getUsedVersions(SSAUConstructorSparseEx ssa, VarVersionPair var, List<VarVersionNode> res) { VarVersionsGraph ssuversions = ssa.getSsuversions(); VarVersionNode varnode = ssuversions.nodes.getWithKey(var); HashSet<VarVersionNode> setVisited = new HashSet<>(); HashSet<VarVersionNode> setNotDoms = new HashSet<>(); LinkedList<VarVersionNode> stack = new LinkedList<>(); stack.add(varnode); while (!stack.isEmpty()) { VarVersionNode nd = stack.remove(0); setVisited.add(nd); if (nd != varnode && (nd.flags & VarVersionNode.FLAG_PHANTOM_FINEXIT) == 0) { res.add(nd); } for (VarVersionEdge edge : nd.succs) { VarVersionNode succ = edge.dest; if (!setVisited.contains(edge.dest)) { boolean isDominated = true; for (VarVersionEdge prededge : succ.preds) { if (!setVisited.contains(prededge.source)) { isDominated = false; break; } } if (isDominated) { stack.add(succ); } else { setNotDoms.add(succ); } } } } setNotDoms.removeAll(setVisited); return !setNotDoms.isEmpty(); }
8
private synchronized void updateScore(double counter, int color, int i) { // score how interesting this point is if (smart_random_points_score[color][i] > 0) smart_random_points_score[color][i] = 0.5 * counter + 0.5 * smart_random_points_score[color][i]; else smart_random_points_score[color][i] = counter; // if we are struggling and expanded the search zone, give points that // actually display a +1 bonus if (border_buffer > 40) { int roundCounter = (int) counter; double countDiff = ((double) roundCounter) - counter; if (countDiff != 0) smart_random_points_score[color][i] += 1; } // if the point had more than one hit, keep it if (smart_random_points_score[color][i] > 1.1) { accepted++; double factor = 0.01; if (smart_random_points_score[color][i] > avg_score[color] * (1.2 + zoom)) { // procreate this extra good point smart_random_points[color][replacePoint[color][0]][0] = smart_random_points[color][i][0] + (Math.random() - 0.5) * factor * zoom; smart_random_points[color][replacePoint[color][0]][1] = smart_random_points[color][i][1] + (Math.random() - 0.5) * factor * zoom; // overwrite a previously identified weak point int k = 0; for (k = 0; k < replacePoint[color].length - 1; k++) { replacePoint[color][k] = replacePoint[color][k + 1]; } replacePoint[color][k - 1] = i; } // cull some points if (avg_score[color] > 3 && i % 3 == 0) factor = factor * 5; // this is an interesting point, try another one near it next time smart_random_points[color][i][0] += (Math.random() - 0.5) * factor * zoom; smart_random_points[color][i][1] += (Math.random() - 0.5) * factor * zoom; } else { // try another random point rejected++; smart_random_points_score[color][i] = 0; smart_random_points[color][i][0] = Math.random(); smart_random_points[color][i][1] = Math.random(); // add this weak point to the front of the list int k = 1; for (k = 1; k < replacePoint[color].length; k++) { replacePoint[color][k] = replacePoint[color][k - 1]; } replacePoint[color][0] = i; } }
9
public static int[] bufferStringChunkUTF8(CharSequence s, int start, byte[] byteBuffer) throws IOException { int bufferPos = 0; int stringPos = start; while (stringPos < s.length()) { char ch = s.charAt(stringPos); int encodingSize = utf8EncodingSize(ch); if ((bufferPos + encodingSize) > byteBuffer.length) { break; } switch (encodingSize) { case 1: byteBuffer[bufferPos++] = (byte) ch; break; case 2: byteBuffer[bufferPos++] = (byte) (0xc0 | ch >> 6 & 0x1f); byteBuffer[bufferPos++] = (byte) (0x80 | ch >> 0 & 0x3f); break; case 3: byteBuffer[bufferPos++] = (byte) (0xe0 | ch >> 12 & 0x0f); byteBuffer[bufferPos++] = (byte) (0x80 | ch >> 6 & 0x3f); byteBuffer[bufferPos++] = (byte) (0x80 | ch >> 0 & 0x3f); break; } stringPos++; } return new int[] {stringPos, bufferPos}; }
5
public int getX(){ return xPos; }
0
public Rule[] Scan(String fileName) { try { InputStream inputStream = getClass().getClassLoader().getResourceAsStream(fileName); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); ArrayList<String> tempLines = new ArrayList<String>(); String line = ""; while((line = reader.readLine()) != null) { tempLines.add(line); } reader.close(); String[] lines = tempLines.toArray(new String[tempLines.size()]); Rule[] rules = new Rule[lines.length]; if(lines != null) { for(int i = 0; i < lines.length; i++) { rules[i] = new Rule(lines[i]); } } return rules; } catch(IOException e) { System.err.print(e.toString()); return null; } }
4
public boolean startDragComponent(Point p) { clearDragState(); // which component is dragged ? for(int i = 0; i < getTabCount(); i++) { Rectangle tabbounds = getBoundsAt(i); if(tabbounds != null && tabbounds.contains(p)) { draggedDockable = (SingleDockableContainer) getComponentAt(i); if(i > 2 && i == getTabCount() - 1) { // workaround for a focus problem : when the JTabbedPane has focus on the last tab // and we start a drag (and drop outside the tabbedpane, there is a // nonblocking stacktrace due to a bad focusIndex in BasicTabbedPaneUI (method focusLost() of the Handler) KeyboardFocusManager.getCurrentKeyboardFocusManager().upFocusCycle(); // by putting the focus up before the drop occurs, we ensure a good focusIndex is set } return true; } } // search for whole tab drag : look after last tab and in-between tabs Rectangle header = getBoundsAt(0); if (header == null) { return false; } header.x = 0; int lastTab = getTabCount() - 1; Rectangle lasttabbounds = getBoundsAt(lastTab); if (lasttabbounds == null) { return false; } header = header.union(lasttabbounds); Rectangle afterlast = new Rectangle(lasttabbounds.x + lasttabbounds.width, lasttabbounds.y, getX() + getWidth() - (lasttabbounds.x + lasttabbounds.width), lasttabbounds.height); if(afterlast.contains(p) || header.contains(p)) { // either after the last tab or between tabs this.isMultipleDrag = true; return true; } return false; }
9
private int spareBonus(Frame [] frame, int thisIndex, int frameNum) { if (thisIndex < 9 && thisIndex + 1 > frameNum) return -1; return frame[thisIndex + 1].first; }
2
void run(){ int N = 150000; Scanner sc = new Scanner(System.in); boolean[] p = new boolean[N]; Arrays.fill(p, true); List<Integer> l = new ArrayList<Integer>(); p[0]=p[1]=false; for(int i=2;i<N;i++){ if(p[i]){ l.add(i); for(int j=i+i;j<N;j+=i)p[j]=false; } } for(;;){ int n = sc.nextInt(), P = sc.nextInt(); if(n==-1&&P==-1)break; List<Integer> res = new ArrayList<Integer>(); int k=0; while(l.get(k)<=n)k++; for(int i=k;i<k+P;i++)for(int j=i;j<k+P;j++)res.add(l.get(i)+l.get(j)); Collections.sort(res); System.out.println(res.get(P-1)); } }
9
private static void writeTo(String outputFileName, ArrayList<String> lines) throws IOException { PrintWriter writer; if (outputFileName == null) { throw new IOException("No file has been loaded."); } writer = new PrintWriter(new FileOutputStream(outputFileName)); for (String line : lines) { writer.println(line); } writer.close(); }
2
public Production getProductionForTransition(Transition transition) { FSATransition trans = (FSATransition) transition; State toState = trans.getToState(); State fromState = trans.getFromState(); String label = trans.getLabel(); String lhs = (String) MAP.get(fromState); String rhs = label.concat((String) MAP.get(toState)); Production production = new Production(lhs, rhs); return production; }
0
public Piece.TypePiece askPromotion(ChessGame G){ String L = null; Piece.TypePiece type = Piece.TypePiece.P; System.out.println("Write the piece you want(one character) :"); System.out.println("\"P\" : Pawn"); System.out.println("\"B\" : Bishop"); System.out.println("\"N\" : Knight"); System.out.println("\"R\" : Rook"); System.out.println("\"Q\" : Queen"); boolean ok = true; do { while(((L=sc.nextLine()).length())!=1) { System.out.println("Error.\nTry again."); } switch (L) { default : ok = false; break; case "P" : type = Piece.TypePiece.P; break; //Bw or Bb will do case "B" : type = Piece.TypePiece.Bb; break; case "N" : type = Piece.TypePiece.Kn; break; case "R" : type = Piece.TypePiece.R; break; case "Q" : type = Piece.TypePiece.Q; break; } }while (!ok); return type; }
7
private static int[] merge(int[] left, int[] right) { // Lengths of both lists int leftLength = left.length; int rightLength = right.length; int[] result = new int[leftLength + rightLength]; // Sets of indexes int idx = 0; int leftIdx = 0; int rightIdx = 0; // Goes through both lists (as long as there are any elements in either of them) while (leftLength > 0 || rightLength > 0) { // Checks if both lists have elements if (leftLength > 0 && rightLength > 0) { if (left[leftIdx] <= right[rightIdx]) { result[idx++] = left[leftIdx++]; --leftLength; } else { result[idx++] = right[rightIdx++]; --rightLength; } } // Add the current element of the left list else if (leftLength > 0) { result[idx++] = left[leftIdx++]; --leftLength; } // Add the current element of the right list else if (rightLength > 0) { result[idx++] = right[rightIdx++]; --rightLength; } } return result; }
7
public Song removeSong(String path) { if(path == null || path.equals("")) return null; Song result= this.songMap.remove(path); return result; }
2
static public DalcSong getInstance() { if (m_instance == null) { m_instance = new DalcSong(); } return m_instance; }
1
@After public void tearDown() { }
0
private ConvertiblePair getRequiredTypeInfo(Object converter) { return ((Converter<?, ?>) converter).getConvertibleType(); }
2
@Override public long clean(long bytesToClean) { if (isEmptyStorage()) return 0; long cleanedBytes = 0; for (Map.Entry<FileTime, File> fileEntry : cachedFiles.entrySet()) { try { final File oldFile = fileEntry.getValue(); final long fileSize = oldFile.length(); if(deleteFile(oldFile)){ cachedFiles.remove(fileEntry.getKey()); cleanedBytes += fileSize; } } catch (FileNotFoundException e) { e.printStackTrace(); } if ((cleanedBytes > bytesToClean) || isEmptyStorage()) break; } return cleanedBytes; }
6
@Before public void setUp() { this.p = new Piste(0, 0); this.e = new Este(0, 0, 10, 10); this.t = new Taso(); }
0
private static int loadShader(String path, int type) { StringBuilder source = new StringBuilder(); try { BufferedReader reader = new BufferedReader(new FileReader(path)); String line; while ((line = reader.readLine()) != null) { source.append(line).append("\n"); } reader.close(); System.out.println(source); } catch (FileNotFoundException ex) { System.err.printf("Shader source not found: %s\n", path); System.exit(-1); } catch (IOException ex) { System.err.printf("Could not read shader source: %s\n", path); System.exit(-1); } int shaderID = glCreateShader(type); glShaderSource(shaderID, source); glCompileShader(shaderID); return shaderID; }
3
void append(DNSIncoming that) { if (this.isQuery() && this.isTruncated() && that.isQuery()) { if (that.numQuestions > 0) { if (Collections.EMPTY_LIST.equals(this.questions)) this.questions = Collections.synchronizedList(new ArrayList(that.numQuestions)); this.questions.addAll(that.questions); this.numQuestions += that.numQuestions; } if (Collections.EMPTY_LIST.equals(answers)) { answers = Collections.synchronizedList(new ArrayList()); } if (that.numAnswers > 0) { this.answers.addAll(this.numAnswers, that.answers.subList(0, that.numAnswers)); this.numAnswers += that.numAnswers; } if (that.numAuthorities > 0) { this.answers.addAll(this.numAnswers + this.numAuthorities, that.answers.subList(that.numAnswers, that.numAnswers + that.numAuthorities)); this.numAuthorities += that.numAuthorities; } if (that.numAdditionals > 0) { this.answers.addAll(that.answers.subList(that.numAnswers + that.numAuthorities, that.numAnswers + that.numAuthorities + that.numAdditionals)); this.numAdditionals += that.numAdditionals; } } else { throw new IllegalArgumentException(); } }
9
public PassengerTrain buildPassengerTrain() throws OutOfRangeException { PassengerTrain res = new PassengerTrain(); res.clear(); Random rand = new Random(); res.add(new Locomotive.Creator().setHorsePowers(4400).setModel("ES44C4").setEngine("GEVO-12") .setTonsWeight(126).setHeight(4.588).setComfortPercent(20).create()); res.add(new Locomotive.Creator().setHorsePowers(4250).setModel("P42DC").setEngine("GE 7FDL-16") .setTonsWeight(135).setHeight(4.600).setComfortPercent(40).create()); RailwayVehicleFactory vehicleFactory = new PassengerCarFactory(); double height = (rand.nextDouble()/2+0.5)*RailwayVehicle.MAX_HEIGHT; for ( int i = 0; i < passengerCarsCnt; i++ ){ PassengerCar pCar = (PassengerCar) vehicleFactory.getRailwayVehicle(); pCar.setHeight(height); pCar.setComfortPercent( rand.nextDouble()*100 ); pCar.setBaggageWeight( rand.nextDouble()*PassengerCar.MAX_BAGGAGE_WEIGHT); pCar.setPassengersCount( (int)(rand.nextDouble()*PassengerCar.MAX_PASSENGER_SCOUNT) ); pCar.setTonsWeight( rand.nextDouble()*PassengerCar.MAX_TONS_WEIGHT ); res.add( pCar ); } return res; }
1
private OBJIndex ParseOBJIndex(String token) { String[] values = token.split("/"); OBJIndex result = new OBJIndex(); result.SetVertexIndex(Integer.parseInt(values[0]) - 1); if(values.length > 1) { if(!values[1].isEmpty()) { m_hasTexCoords = true; result.SetTexCoordIndex(Integer.parseInt(values[1]) - 1); } if(values.length > 2) { m_hasNormals = true; result.SetNormalIndex(Integer.parseInt(values[2]) - 1); } } return result; }
3
private void outputErrorDialog(JTextPane pane){ Scanner fileScanner; System.out.println("Default Output Error File Path: " + outputErrorFilePath); try { if(!outputErrorFilePath.contains("src/")){ outputErrorFilePath = "src/" + outputErrorFilePath; } fileScanner = new Scanner(new FileInputStream(outputErrorFilePath)); writeOutput(pane, "\nOutput Error File : " + outputErrorFilePath); writeOutput(pane, "_______________"); while(fileScanner.hasNextLine()){ writeOutput(pane, fileScanner.nextLine()); } fileScanner.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } }
3
public Double aStarSearch(Vertex[] vertices, int start, int goal) { PriorityQueue<Vertex> vertexQueue = new PriorityQueue<Vertex>(); vertices[start].gScore = 0.0; vertices[goal].isGoal = true; vertexQueue.add(vertices[start]); while (!vertexQueue.isEmpty()) { Vertex current = vertexQueue.poll(); if (current.isGoal) { return vertices[goal].gScore; } current.visited = true; vertices[current.vertexID].visited = true; // for all vertex adjacent to current do for (int n = 0; n < vertices.length; n++) { if (current.adjList.contains(n) && !vertices[n].visited) { Vertex adj = vertices[n]; Double gScore = current.gScore + euclidianDistance(current, adj); // if adj not in Q or gScore < adj.gScore if (!vertexQueue.contains(adj) || gScore < adj.gScore) { // Update the Scores for the adjacent vertex. vertexQueue.remove(adj); adj.gScore = gScore; adj.hScore = euclidianDistance(adj, vertices[goal]); adj.fScore = adj.gScore + adj.hScore; // Add this vertex back into the priority queue with updated information. vertexQueue.add(adj); } } } } // Failed. return Double.POSITIVE_INFINITY; }
7
private void drawtile(GOut g, Coord tc, Coord sc) { Tile t; try { t = getground(tc); // t = gettile(tc).ground.pick(0); g.image(t.tex(), sc); // g.setColor(FlowerMenu.pink); // Utils.drawtext(g, Integer.toString(t.i), sc); if (Config.tileAA) { for (Tile tt : gettrans(tc)) { g.image(tt.tex(), sc); } } } catch (Loading e) { } }
3
public SEccl(String arg, Int i) { i.incr(); /* skip over '[' */ if (i.get()>=arg.length()) throw new RESyntaxException("pattern ends with ["); if (arg.charAt(i.get()) == RE.NEGCCL) { negate = true; i.incr(); } // Expand the range doDash(arg, i); if (arg.charAt(i.get()) != RE.CCLEND) throw new RESyntaxException("CCL ends without ]"); }
3
public void loadConfigFiles() { try { loadRoomConfig(); loadBoardConfig(); cellXSize = (BOARDDIMENSIONX)/numColumns; cellYSize = (BOARDDIMENSIONY)/numRows; } catch (BadConfigFormatException b) { new BadConfigFormatException(b.getMessage()); } catch (FileNotFoundException e) { new BadConfigFormatException(e.getMessage()); } }
2
void passf2(int ido, int l1, final double cc[], double ch[], final double wtable[], int offset, int isign) /*isign==+1 for backward transform*/ { int i, k, ah, ac; double ti2, tr2; int iw1; iw1 = offset; if(ido<=2) { for(k=0; k<l1; k++) { ah=k*ido; ac=2*k*ido; ch[ah]=cc[ac]+cc[ac+ido]; ch[ah+ido*l1]=cc[ac]-cc[ac+ido]; ch[ah+1]=cc[ac+1]+cc[ac+ido+1]; ch[ah+ido*l1+1]=cc[ac+1]-cc[ac+ido+1]; } } else { for(k=0; k<l1; k++) { for(i=0; i<ido-1; i+=2) { ah=i+k*ido; ac=i+2*k*ido; ch[ah]=cc[ac]+cc[ac+ido]; tr2=cc[ac]-cc[ac+ido]; ch[ah+1]=cc[ac+1]+cc[ac+1+ido]; ti2=cc[ac+1]-cc[ac+1+ido]; ch[ah+l1*ido+1]=wtable[i+iw1]*ti2+isign*wtable[i+1+iw1]*tr2; ch[ah+l1*ido]=wtable[i+iw1]*tr2-isign*wtable[i+1+iw1]*ti2; } } } }
4
private Manufacturer(int id, String name) { this.id = (byte) id; this.name = name; }
0
@SuppressWarnings("rawtypes") public void setValidator(Validator validator) { this.validator = validator; }
0
public void bombbrick(int c, int r) { // The number of bricks removed (the effectiveness of the bomb) depends on level int remove; if (level == 1) remove = 2; else remove = 1; // Makes bricks invisible for (int i = c - remove; i <= c + remove; i++) { for (int j = r - remove; j <= r + remove; j++) { if (i >= 0 && i < bricks.length && j >= 0 && j < bricks[0].length) { bricks[i][j].state = false; } } } }
7
public void addDefault(String node, String value) { boolean flag = false; this.pattern = Pattern .compile("^<node=\"([-_a-zA-Z,._\\/0-9]{1,})\">([-a-zA-Z,._\\/0-9\\s]{1,})<\\/node>"); String tmp = ""; for (String line : this.getConfigFileLines()) { this.matcher = this.pattern.matcher(line); if (this.matcher.matches()) { tmp = this.matcher.group(1); if (tmp.equals(node)) { flag = true; } } } if (!flag) { this.getConfigFileLines().add( "<node=\"" + node + "\">" + value + "</node>"); } }
4
protected void setWindowSize(int _width, int _height) { this.width = _width; this.height = _height; updateAspectRatio(); }
0
private static void readHeader(ObjectInputStream ois, int[] header) throws IOException { for(int i = 0; i < 128; i++) { header[i] = ois.readInt(); } textLength = ois.readInt(); }
1
public OBJModel(String fileName) { m_positions = new ArrayList<Vector3f>(); m_texCoords = new ArrayList<Vector2f>(); m_normals = new ArrayList<Vector3f>(); m_indices = new ArrayList<OBJIndex>(); m_hasTexCoords = false; m_hasNormals = false; BufferedReader meshReader = null; try { meshReader = new BufferedReader(new FileReader(fileName)); String line; while((line = meshReader.readLine()) != null) { String[] tokens = line.split(" "); tokens = Util.RemoveEmptyStrings(tokens); if(tokens.length == 0 || tokens[0].equals("#")) continue; else if(tokens[0].equals("v")) { m_positions.add(new Vector3f(Float.valueOf(tokens[1]), Float.valueOf(tokens[2]), Float.valueOf(tokens[3]))); } else if(tokens[0].equals("vt")) { m_texCoords.add(new Vector2f(Float.valueOf(tokens[1]), 1.0f - Float.valueOf(tokens[2]))); } else if(tokens[0].equals("vn")) { m_normals.add(new Vector3f(Float.valueOf(tokens[1]), Float.valueOf(tokens[2]), Float.valueOf(tokens[3]))); } else if(tokens[0].equals("f")) { for(int i = 0; i < tokens.length - 3; i++) { m_indices.add(ParseOBJIndex(tokens[1])); m_indices.add(ParseOBJIndex(tokens[2 + i])); m_indices.add(ParseOBJIndex(tokens[3 + i])); } } } meshReader.close(); } catch(Exception e) { e.printStackTrace(); System.exit(1); } }
9
protected void Update(double timeDelta) { m_elapsedTime = (m_currentTime - m_startTime) / 1000.0f;//time, in seconds, since creation of GameForm m_currentFPS = Math.floor(1000.0 / timeDelta);//estimated FPS at this instant in time, rounded down if (IsKeyTriggered(KeyEvent.VK_F11))//toggle fullscreen { m_isFullScreen = !m_isFullScreen; this.setSize(m_isFullScreen ? m_fullScreenSize : m_windowedSize); if (m_isFullScreen) this.setLocation(0, 0);//so that the full window is visible else this.setLocationRelativeTo(null);//center screen } if (IsKeyPressed(KeyEvent.VK_ESCAPE)) System.exit(0); }
4
void updateCamera() { if (KeyInput.isKeyDown(Keyboard.KEY_UP )) pushCamera(-1, 1) ; if (KeyInput.isKeyDown(Keyboard.KEY_DOWN )) pushCamera( 1, -1) ; if (KeyInput.isKeyDown(Keyboard.KEY_RIGHT)) pushCamera( 1, 1) ; if (KeyInput.isKeyDown(Keyboard.KEY_LEFT )) pushCamera(-1, -1) ; //if (KeyInput.isKeyDown(Keyboard.KEY_SPACE)) zoomHome() ; if (lockTarget != null) followLock() ; }
5
public void visit_freturn(final Instruction inst) { stackHeight -= 1; if (stackHeight < minStackHeight) { minStackHeight = stackHeight; } }
1
public int getInt(int index) throws JSONException { Object object = this.get(index); try { return object instanceof Number ? ((Number) object).intValue() : Integer.parseInt((String) object); } catch (Exception e) { throw new JSONException("JSONArray[" + index + "] is not a number."); } }
2
@Override public String toString() { return String.format( "annotatedWith(%s)", this.annotationType.getName() ); }
0
public void actionPerformed(ActionEvent e) { try { if (e.getActionCommand().equals("Scout")) { //Creates an instance of the scout frame ScouterScreen a = new ScouterScreen(); //Hide the page this.setVisible(false); } else if (e.getActionCommand().equals("Import")) { //Method call to import data from file importFile(); //Reload the screen with updated table HomeScreen a = new HomeScreen(); //Hide the old page this.setVisible(false); } else if (e.getActionCommand().equals("Export")) { JOptionPane.showMessageDialog(null, "To export stats for use of" + " another computer: \n\n1. Copy the database text file to" + " the new computer \n2. Open the database you wish to" + " import into \n3. Click import and select the file"); } else if (e.getActionCommand().equals("SearchBox")) { txtSearch.setText(null); txtSearch.grabFocus(); } else if (e.getActionCommand().equals("Search")) { search(); } else if (e.getActionCommand().equals("Help")) { Help a = new Help(); } else if (e.getActionCommand().equals("Back")) { //Create a new instance of the welcome screen if( JOptionPane.showConfirmDialog(null, "Continuing will " + "close your current file. Continue anyways?", "Import", JOptionPane.CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE) == 0) { //Clear cached database clearCache(); WelcomeScreen a = new WelcomeScreen(); } //Hide this page this.setVisible(false); } }//End of try catch(Exception ex) { JOptionPane.showMessageDialog(null, "Please enter a valid team number."); } }//End of actionPerformed()
9
public void backTrack() { boolean tmpCounter = false, skipCounter = false; for(int i = closedNodes.size()-1; i >= 0; i--) { skipCounter = false; for (Node tmpDead : deadEndList) { if((closedNodes.get(i).compareTo(tmpDead))==1){ skipCounter = true; break; } } if(skipCounter==false) { this.currentNode = closedNodes.get(i); this.checkerObject.nodeCheckAll(closedNodes.get(i), closedNodes); if((checkerObject.getUp()==1)||(checkerObject.getLeft()==1)||(checkerObject.getDown()==1)||(checkerObject.getRight()==1)) { return; } deadEndList.add(this.currentNode); if(tmpCounter==true) { this.view.printMaze(this.currentNode, this.closedNodes); this.expandCounter++; this.view.printCounter(this.expandCounter); } tmpCounter = true; // Toggle counter to start adding a step } } }
9
public boolean pass(int[] bowl, int bowlId, int round, boolean canPick, boolean musTake) { counter++; if(counter==1){ for(int i=0;i<12;i++){ bowSize+=bowl[i]; } //update(bowSize*6); } update(bowl,bowlId,round); if (musTake){ return true; } if(canPick==false) return false; //no enough information if (info.size()<=1) { return false; } if (round==0) { futureBowls=nplayer-position-counter; //return round0(bowl,bowlId,round,canPick,musTake); } else { futureBowls=nplayer-counter+1; //return round1(bowl,bowlId,round,canPick,musTake); } double b=score(bowl); double PrB=1, p=probLessThan(b); for (int i = 0; i < futureBowls; i++) { PrB*=p; } double PrA=1-PrB; double ExA=exptGreaterThan(b); double ExB=exptLessThan(b); double Ex2=PrA*ExA+PrB*ExB; double tStar=search(); double fTStar=f(tStar); //double fb=f(b,futureBowls); //double fb1=f(b+1, futureBowls); if(fTStar>b) { // return false; } else { return true; } }
8
public void updateTarget(Target moveTarget) { final Target oldTarget = trueTarget ; this.trueTarget = moveTarget ; if (trueTarget != oldTarget) { if (verbose) I.sayAbout(mobile, "...TARGET HAS CHANGED: "+trueTarget) ; path = null ; stepIndex = -1 ; return ; } else if (inLocus(nextStep())) { stepIndex = Visit.clamp(stepIndex + 1, path.length) ; } else if (verbose) I.sayAbout(mobile, "Not in locus of: "+nextStep()) ; }
4
public void run () { while (directory_prefix != null) { // No matter how we learn that something may have // changed, we do the same thing to figure out // exactly what changed: scan usbdevfs scanForDevices(matchUSBvendorID,matchUSBproductID); //while (scan ()) // continue; try { Thread.sleep (POLL_PERIOD_MS); } catch (InterruptedException e) { // set dir to null to cause a clean exit directory_prefix = null; } } }
2
static public void main(String args[]) throws Exception { if (args.length <= 0) { System.err.println("Usage: java MultiPortEcho port [port port ...]"); System.exit(1); } int ports[] = new int[args.length]; for (int i = 0; i < args.length; ++i) { ports[i] = Integer.parseInt(args[i]); } new NIOEchoServer(ports); }
2
@Override public void setAccounting(Accounting accounting) { counterParties = (CounterParties)accounting.getBusinessObject(CounterParties.COUNTERPARTIES); statements = (Statements)accounting.getBusinessObject(Statements.STATEMENTS); accounts=accounting==null?null:accounting.getAccounts(); journals=accounting==null?null:accounting.getJournals(); }
2
public Help() { setTitle("AYUDA"); setIconImage(Toolkit.getDefaultToolkit().getImage(Help.class.getResource("/InterfazGrafica/Images/1416396005_FAQ.png"))); setBounds(10, 50, 836, 739); setLocationRelativeTo(rootPane); setModal(true); getContentPane().setLayout(new BorderLayout()); contentPanel.setBackground(new Color(248, 248, 255)); contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5)); getContentPane().add(contentPanel, BorderLayout.CENTER); contentPanel.setLayout(null); { JPanel panel = new JPanel(); panel.setBackground(new Color(248, 248, 255)); panel.setForeground(new Color(0, 0, 0)); panel.setBounds(36, 11, 227, 332); panel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), " Inicio", TitledBorder.LEFT, TitledBorder.ABOVE_TOP, null, null)); contentPanel.add(panel); panel.setLayout(null); { JLabel label = new JLabel(""); label.setIcon(new ImageIcon(Help.class.getResource("/InterfazGrafica/Images/1416514885_home.png"))); label.setBounds(10, 0, 46, 48); panel.add(label); } { JLabel lblPermiteAccederDirectamente = new JLabel("Permite acceder directamente a las "); lblPermiteAccederDirectamente.setFont(lblPermiteAccederDirectamente.getFont().deriveFont(lblPermiteAccederDirectamente.getFont().getStyle() & ~Font.BOLD)); lblPermiteAccederDirectamente.setBounds(10, 59, 231, 14); panel.add(lblPermiteAccederDirectamente); } { JLabel lblPrincipalesHerramientasDel = new JLabel("principales herramientas b\u00E1sicas del "); lblPrincipalesHerramientasDel.setFont(lblPrincipalesHerramientasDel.getFont().deriveFont(lblPrincipalesHerramientasDel.getFont().getStyle() & ~Font.BOLD)); lblPrincipalesHerramientasDel.setBounds(10, 77, 231, 14); panel.add(lblPrincipalesHerramientasDel); } { JLabel lblMencionadasAContinuacin = new JLabel("sistema mencionadas a continuaci\u00F3n:"); lblMencionadasAContinuacin.setFont(lblMencionadasAContinuacin.getFont().deriveFont(lblMencionadasAContinuacin.getFont().getStyle() & ~Font.BOLD)); lblMencionadasAContinuacin.setBounds(10, 93, 231, 14); panel.add(lblMencionadasAContinuacin); } { JLabel lblNuevoCliente = new JLabel("Nuevo Cliente "); lblNuevoCliente.setIcon(new ImageIcon(Help.class.getResource("/InterfazGrafica/Images/Add32.png"))); lblNuevoCliente.setBounds(10, 118, 172, 32); panel.add(lblNuevoCliente); } { JLabel lblNuevaSolicitud = new JLabel("Nueva Solicitud"); lblNuevaSolicitud.setIcon(new ImageIcon(Help.class.getResource("/InterfazGrafica/Images/1417568890_new-file.png"))); lblNuevaSolicitud.setBounds(10, 161, 172, 32); panel.add(lblNuevaSolicitud); } { JLabel lblBuscar = new JLabel("Buscar"); lblBuscar.setIcon(new ImageIcon(Help.class.getResource("/InterfazGrafica/Images/Search32.png"))); lblBuscar.setLabelFor(this); lblBuscar.setBounds(10, 204, 172, 32); panel.add(lblBuscar); } { JLabel lblAyuda = new JLabel("Ayuda"); lblAyuda.setIcon(new ImageIcon(Help.class.getResource("/InterfazGrafica/Images/Ayuda32.png"))); lblAyuda.setBounds(10, 247, 172, 32); panel.add(lblAyuda); } { JLabel lblCerrar = new JLabel("Cerrar"); lblCerrar.setIcon(new ImageIcon(Help.class.getResource("/InterfazGrafica/Images/Delete32.png"))); lblCerrar.setBounds(10, 290, 172, 32); panel.add(lblCerrar); } } { JPanel panel = new JPanel(); panel.setLayout(null); panel.setForeground(Color.BLACK); panel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), " Registrar", TitledBorder.LEFT, TitledBorder.ABOVE_TOP, null, null)); panel.setBackground(new Color(248, 248, 255)); panel.setBounds(297, 11, 227, 332); contentPanel.add(panel); { JLabel label = new JLabel(""); label.setIcon(new ImageIcon(Help.class.getResource("/InterfazGrafica/Images/Modify.png"))); label.setBounds(10, 0, 46, 48); panel.add(label); } { JLabel lblPermiteRegistrarNuevos = new JLabel("Permite registrar nuevos datos en el"); lblPermiteRegistrarNuevos.setFont(lblPermiteRegistrarNuevos.getFont().deriveFont(lblPermiteRegistrarNuevos.getFont().getStyle() & ~Font.BOLD)); lblPermiteRegistrarNuevos.setBounds(10, 59, 231, 14); panel.add(lblPermiteRegistrarNuevos); } { JLabel lblSistemaYaSea = new JLabel("sistema, sea un nuevo cliente \u00F3 una "); lblSistemaYaSea.setFont(lblSistemaYaSea.getFont().deriveFont(lblSistemaYaSea.getFont().getStyle() & ~Font.BOLD)); lblSistemaYaSea.setBounds(10, 77, 231, 14); panel.add(lblSistemaYaSea); } { JLabel lblNuevaSolicitudDe = new JLabel("nueva solicitud de empleo o personal."); lblNuevaSolicitudDe.setFont(lblNuevaSolicitudDe.getFont().deriveFont(lblNuevaSolicitudDe.getFont().getStyle() & ~Font.BOLD)); lblNuevaSolicitudDe.setBounds(10, 93, 231, 14); panel.add(lblNuevaSolicitudDe); } { JLabel lblSolicitante = new JLabel("Solicitante"); lblSolicitante.setIcon(new ImageIcon(Help.class.getResource("/InterfazGrafica/Images/Profile.png"))); lblSolicitante.setBounds(10, 134, 172, 49); panel.add(lblSolicitante); } { JLabel lblEmpresa = new JLabel("Empresa"); lblEmpresa.setIcon(new ImageIcon(Help.class.getResource("/InterfazGrafica/Images/1416396195_Company.png"))); lblEmpresa.setBounds(10, 194, 172, 48); panel.add(lblEmpresa); } { JLabel lblSolicitudes = new JLabel("Solicitudes"); lblSolicitudes.setVerticalAlignment(SwingConstants.TOP); lblSolicitudes.setIcon(new ImageIcon(Help.class.getResource("/InterfazGrafica/Images/Info.png"))); lblSolicitudes.setBounds(10, 253, 182, 48); panel.add(lblSolicitudes); } } { JPanel panel = new JPanel(); panel.setLayout(null); panel.setForeground(Color.BLACK); panel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), " Base de Datos", TitledBorder.LEFT, TitledBorder.ABOVE_TOP, null, null)); panel.setBackground(new Color(248, 248, 255)); panel.setBounds(564, 11, 227, 332); contentPanel.add(panel); { JLabel label = new JLabel(""); label.setIcon(new ImageIcon(Help.class.getResource("/InterfazGrafica/Images/1416395841_archive.png"))); label.setBounds(10, 0, 46, 48); panel.add(label); } { JLabel lblPermiteAccederA = new JLabel("Permite acceder a todos los archivos"); lblPermiteAccederA.setFont(lblPermiteAccederA.getFont().deriveFont(lblPermiteAccederA.getFont().getStyle() & ~Font.BOLD)); lblPermiteAccederA.setBounds(10, 59, 231, 14); panel.add(lblPermiteAccederA); } { JLabel lblArchivosGuardadosDentro = new JLabel("donde se encuentran los datos de los "); lblArchivosGuardadosDentro.setFont(lblArchivosGuardadosDentro.getFont().deriveFont(lblArchivosGuardadosDentro.getFont().getStyle() & ~Font.BOLD)); lblArchivosGuardadosDentro.setBounds(10, 77, 231, 14); panel.add(lblArchivosGuardadosDentro); } { JLabel lblClientesRegistrados = new JLabel("clientes registrados en el sistema."); lblClientesRegistrados.setFont(lblClientesRegistrados.getFont().deriveFont(lblClientesRegistrados.getFont().getStyle() & ~Font.BOLD)); lblClientesRegistrados.setBounds(10, 93, 231, 14); panel.add(lblClientesRegistrados); } { JLabel lblreasDisponibles = new JLabel("\u00C1reas Disponibles"); lblreasDisponibles.setIcon(new ImageIcon(Help.class.getResource("/InterfazGrafica/Images/areas.png"))); lblreasDisponibles.setBounds(10, 134, 172, 43); panel.add(lblreasDisponibles); } { JLabel lblRegistros = new JLabel("Registros "); lblRegistros.setIcon(new ImageIcon(Help.class.getResource("/InterfazGrafica/Images/Modify.png"))); lblRegistros.setBounds(10, 194, 172, 48); panel.add(lblRegistros); } { JLabel lblSolicitudes_1 = new JLabel("Solicitudes"); lblSolicitudes_1.setIcon(new ImageIcon(Help.class.getResource("/InterfazGrafica/Images/Info.png"))); lblSolicitudes_1.setBounds(10, 253, 172, 48); panel.add(lblSolicitudes_1); } } { JPanel panel = new JPanel(); panel.setLayout(null); panel.setForeground(Color.BLACK); panel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), " Reportes", TitledBorder.LEFT, TitledBorder.ABOVE_TOP, null, null)); panel.setBackground(new Color(248, 248, 255)); panel.setBounds(164, 360, 227, 279); contentPanel.add(panel); { JLabel label = new JLabel(""); label.setIcon(new ImageIcon(Help.class.getResource("/InterfazGrafica/Images/Bar Chart.png"))); label.setBounds(10, 0, 46, 48); panel.add(label); } { JLabel lblPermiteVisualizarLa = new JLabel("Permite llevar estadisticas del Sistema "); lblPermiteVisualizarLa.setFont(lblPermiteVisualizarLa.getFont().deriveFont(lblPermiteVisualizarLa.getFont().getStyle() & ~Font.BOLD)); lblPermiteVisualizarLa.setBounds(10, 59, 231, 14); panel.add(lblPermiteVisualizarLa); } { JLabel lblRegistradosYSus = new JLabel("y visualizar los listados de solicitudes"); lblRegistradosYSus.setFont(lblRegistradosYSus.getFont().deriveFont(lblRegistradosYSus.getFont().getStyle() & ~Font.BOLD)); lblRegistradosYSus.setBounds(10, 77, 231, 14); panel.add(lblRegistradosYSus); } { JLabel lblSolicitudesRegistradas = new JLabel("pendientes y satisfechas."); lblSolicitudesRegistradas.setFont(lblSolicitudesRegistradas.getFont().deriveFont(lblSolicitudesRegistradas.getFont().getStyle() & ~Font.BOLD)); lblSolicitudesRegistradas.setBounds(10, 93, 231, 14); panel.add(lblSolicitudesRegistradas); } { JLabel lblSolicitudesPendientes = new JLabel("Solicitudes Pendientes"); lblSolicitudesPendientes.setIcon(new ImageIcon(Help.class.getResource("/InterfazGrafica/Images/pendientes.png"))); lblSolicitudesPendientes.setBounds(10, 138, 207, 43); panel.add(lblSolicitudesPendientes); } { JLabel lblSolicitudesSatisfechas = new JLabel("Solicitudes Satisfechas"); lblSolicitudesSatisfechas.setIcon(new ImageIcon(Help.class.getResource("/InterfazGrafica/Images/cheking.png"))); lblSolicitudesSatisfechas.setBounds(10, 205, 207, 48); panel.add(lblSolicitudesSatisfechas); } { JLabel label = new JLabel("Solicitudes"); label.setBounds(10, 264, 172, 48); panel.add(label); } } { JPanel panel = new JPanel(); panel.setLayout(null); panel.setForeground(Color.BLACK); panel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), " Consultar", TitledBorder.LEFT, TitledBorder.ABOVE_TOP, null, null)); panel.setBackground(new Color(248, 248, 255)); panel.setBounds(436, 360, 227, 279); contentPanel.add(panel); { JLabel label = new JLabel(""); label.setIcon(new ImageIcon(Help.class.getResource("/InterfazGrafica/Images/Search48.png"))); label.setBounds(10, 0, 46, 48); panel.add(label); } { JLabel lblPermiteAccederA_1 = new JLabel("Permite consultar todos los registros"); lblPermiteAccederA_1.setFont(lblPermiteAccederA_1.getFont().deriveFont(lblPermiteAccederA_1.getFont().getStyle() & ~Font.BOLD)); lblPermiteAccederA_1.setBounds(10, 59, 231, 14); panel.add(lblPermiteAccederA_1); } { JLabel lblYAccederDirectamente = new JLabel("y acceder directamente a un cliente"); lblYAccederDirectamente.setFont(lblYAccederDirectamente.getFont().deriveFont(lblYAccederDirectamente.getFont().getStyle() & ~Font.BOLD)); lblYAccederDirectamente.setBounds(10, 77, 231, 14); panel.add(lblYAccederDirectamente); } { JLabel lblPorMedioDe = new JLabel("por medio de su ID o RNC."); lblPorMedioDe.setFont(lblPorMedioDe.getFont().deriveFont(lblPorMedioDe.getFont().getStyle() & ~Font.BOLD)); lblPorMedioDe.setBounds(10, 93, 231, 14); panel.add(lblPorMedioDe); } { JLabel lblEmpresa_1 = new JLabel("Empresa"); lblEmpresa_1.setIcon(new ImageIcon(Help.class.getResource("/InterfazGrafica/Images/1416396195_Company.png"))); lblEmpresa_1.setBounds(10, 130, 172, 56); panel.add(lblEmpresa_1); } { JLabel lblSolicitante_1 = new JLabel("Solicitante"); lblSolicitante_1.setIcon(new ImageIcon(Help.class.getResource("/InterfazGrafica/Images/Profile.png"))); lblSolicitante_1.setBounds(10, 205, 172, 48); panel.add(lblSolicitante_1); } { JLabel label = new JLabel("Solicitudes"); label.setBounds(10, 264, 172, 48); panel.add(label); } } { JPanel buttonPane = new JPanel(); buttonPane.setBackground(new Color(248, 248, 255)); buttonPane.setLayout(new FlowLayout(FlowLayout.CENTER)); getContentPane().add(buttonPane, BorderLayout.SOUTH); { JButton okButton = new JButton("Aceptar"); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); } }); okButton.setIcon(new ImageIcon(Help.class.getResource("/InterfazGrafica/Images/botonsi.png"))); okButton.setActionCommand("OK"); buttonPane.add(okButton); getRootPane().setDefaultButton(okButton); } } }
0
private void parse() throws MalformedUriException, MalformedDomainException { int colon = string.lastIndexOf(':'); if (string.charAt(0) == '[') { int bracket = string.indexOf(']'); if (bracket < 0) throw new MalformedUriException(string, "Unmatched escape bracket in IPv6 endpoint!"); if (bracket != colon - 1) throw new MalformedUriException(string, "Expected colon after IPv6 host-part!"); if (-1 < string.indexOf('.')) throw new MalformedUriException(string, "Detected escape brackets for non IPv6 host!"); host = Host.get(string.substring(1, bracket)); } else if (-1 < colon) { host = Host.get(string.substring(0, colon)); } else { host = Host.get(string); } if (-1 < colon) { try { port = Integer.parseInt(string.substring(colon + 1)); } catch (NumberFormatException e) { throw new MalformedUriException(string, "Invalid port number format!"); } if (port < 1 || 65535 < port) throw new MalformedUriException(string, "Port number out of range!"); } }
9
private void doGenBackbonesHelper(String runName, int numMutable, int strandMut[][], double theta, double alpha, int numSteps, Backbone bb, double initFi[], double initPsi[], PrintStream logPS, int curRes){ if (curRes==numMutable){//we have a full backbone conformation, so output outputBB(logPS, numMutable, runName, strandMut, bb); } else { //we only have a partial backbone, so apply changes to the current residue if (curRes==0) System.out.println("Starting.."); //First, move the phi/psi angle to -theta, then apply the changes to +theta, at alpha steps int str = mutRes2Strand[curRes]; int strResNum = strandMut[str][mutRes2StrandMutIndex[curRes]]; //move phi to -(theta+alpha), so that the first move in the *for* statement below goes to -theta bb.applyFiPsi(m,str,strResNum,-(theta+alpha),0); //apply phi changes up to +theta for (int curStepFi=0; curStepFi<numSteps; curStepFi++){ //apply each alpha step up to a displacement of +theta from the initial phi if (curRes==0) System.out.print("*"); bb.applyFiPsi(m,str,strResNum,alpha,0); //move psi to -(theta+alpha), so that the first move in the *for* statement below goes to -theta bb.applyFiPsi(m,str,strResNum,-(theta+alpha),1); for (int curStepPsi=0; curStepPsi<numSteps; curStepPsi++){ //apply each alpha step up to a displacement of +theta from the initial psi if (curRes==0) System.out.print("."); bb.applyFiPsi(m,str,strResNum,alpha,1); if (checkStericsBBonly(str,strResNum)) {//passed steric test, so move to the next residue doGenBackbonesHelper(runName,numMutable,strandMut,theta,alpha,numSteps,bb,initFi,initPsi,logPS,curRes+1); } } //restore initial psi bb.applyFiPsi(m,str,strResNum,-theta,1); if (curRes==0) System.out.println(); } //restore initial phi bb.applyFiPsi(m,str,strResNum,-theta,0); if (curRes==0) System.out.println("done"); } }
9
public static boolean check_variable_name_repeat(Variable_table variable_table, String name) { for (int i = 0; i < variable_table.variable_name.size(); i++) { if (variable_table.variable_name.get(i).toString().equals(name)) { return false; } } return true; }
2
public void date() { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMM"); try { Date date = dateFormat.parse(monthDate); Calendar cal = Calendar.getInstance(); cal.setTime(date); maxDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH); cal.add(Calendar.MONTH, -1); lastMaxDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH); } catch (ParseException e) { e.printStackTrace(); // return error(fileName + " 期数格式不正确!应为yyyyMM"); } }
1
public Job(int id, int tempoDeProcessamento, int requisicoesES, int acessoArquivos, int instanteDeChegada, ArrayList<Arquivo> arquivos) { this.id = id; this.instanteDeChegada = instanteDeChegada; this.tempoDeProcessamento = tempoDeProcessamento; this.requisicoesES = requisicoesES; this.acessoArquivos = acessoArquivos; this.tempoRodado = 0; this.arquivos = arquivos; int tdp = tempoDeProcessamento; Random rd = new Random(id + instanteDeChegada + tempoDeProcessamento + requisicoesES + acessoArquivos); // System.out.println("----"); for(int i = 0; i < requisicoesES; i++) { int tempo = rd.nextInt(tdp / ((requisicoesES - i) * 2)) + tdp / ((requisicoesES - i) * 2); tdp -= tempo; int tempoAnt; try { tempoAnt = tempoRequisicoesES.get(i - 1); } catch (Exception e) { tempoAnt = 0; } tempoRequisicoesES.add(tempo + tempoAnt); // System.out.println(tempo + tempoAnt); } // System.out.println("----"); tdp = tempoDeProcessamento; for(int i = 0; i < acessoArquivos; i++) { int tempo; int tempoAnt; do { tempo = rd.nextInt(tdp / ((acessoArquivos - i) * 2)) + tdp / ((acessoArquivos - i) * 2); tdp -= tempo; try { tempoAnt = tempoAcessoArquivos.get(i - 1); } catch (Exception e) { tempoAnt = 0; } } while(tempoRequisicoesES.contains(tempo + tempoAnt)); tempoAcessoArquivos.add(tempo + tempoAnt); // System.out.println(tempo + tempoAnt); } // System.out.println("----"); for(int tempo : tempoAcessoArquivos) { Arquivo arqAnterior; Arquivo arq; do { arq = arquivos.get(rd.nextInt(arquivos.size())); try { arqAnterior = arquivoAcessadoTempo.get(tempoAcessoArquivos.get(tempoAcessoArquivos.indexOf(tempo) - 1)); } catch(Exception e) { arqAnterior = null; } } while(arq == arqAnterior); arquivoAcessadoTempo.put(tempo, arq); // System.out.println(tempo + ": " + arq.getNome()); } Segmento seg = new Segmento(20); segmentos = new ArvoreN<Segmento>(seg); Segmento seg2 = new Segmento(15); segmentos.addReferencia(seg, seg2); Segmento seg3 = new Segmento(25); segmentos.addReferencia(seg, seg3); Segmento seg4 = new Segmento(10); segmentos.addReferencia(seg3, seg4); segmentoUso = segmentos.getCabeca(); }
8
public static boolean areCompatiable(Width lhs, Width rhs) { return lhs == rhs || (lhs == Width.ScalarDouble && rhs == Width.Quad) || (lhs == Width.Quad && rhs == Width.ScalarDouble) || (lhs == Width.ScalarSingle && rhs == Width.Long) || (lhs == Width.Long && rhs == Width.ScalarSingle); }
8
@Override public boolean createGame(Date date, Member memberOne, Member memberTwo) { Game game = new Game(date, memberOne, memberTwo); List<Game> games = getAllGames(); games.add(game); try { serializeObjectToXML("Games.xml", games); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } return true; }
1
private void unfilterPaeth(byte[] curLine, byte[] prevLine) { final int bpp = this.bytesPerPixel; int i; for (i = 1; i <= bpp; ++i) { curLine[i] += prevLine[i]; } for (int n = curLine.length; i < n; ++i) { int a = curLine[i - bpp] & 255; int b = prevLine[i] & 255; int c = prevLine[i - bpp] & 255; int p = a + b - c; int pa = p - a; if (pa < 0) { pa = -pa; } int pb = p - b; if (pb < 0) { pb = -pb; } int pc = p - c; if (pc < 0) { pc = -pc; } if (pa <= pb && pa <= pc) { c = a; } else if (pb <= pc) { c = b; } curLine[i] += (byte) c; } }
8
public String decodeData(List<Integer> data) { wbDecoding = new HashMap<Integer, String>(); wbEncoding = new HashMap<String, Integer>(); StringBuffer rv = new StringBuffer(); List<StringBuffer> cache = new LinkedList<StringBuffer>(); int nextIndex = 256; for (int i : data) { if (i < 256) { wbEncoding.put(Character.toString((char) i), i); wbDecoding.put(i, Character.toString((char) i)); } rv.append(wbDecoding.get(i)); // process cache entries List<StringBuffer> rm = new LinkedList<StringBuffer>(); for (StringBuffer sbc : cache) { if(wbDecoding.get(i) == null){ System.out.println(i + " is null"); } sbc.append(wbDecoding.get(i).charAt(0)); if (wbEncoding.get(sbc.toString()) == null) { wbEncoding.put(sbc.toString(), nextIndex); wbDecoding.put(nextIndex, sbc.toString()); rm.add(sbc); nextIndex++; } } for (StringBuffer rmb : rm) { cache.remove(rmb); } // add current character to cache cache.add(new StringBuffer(wbDecoding.get(i))); } for (Integer in : wbDecoding.keySet()) { System.out.println(in + ":" + wbDecoding.get(in)); } return rv.toString(); }
7
public void unpauseAll(){ if (paused.size() == 0) return; // Continue all paused sounds: for (Map.Entry<String, Integer> entry : paused.entrySet()){ if (entry.getValue() > 0){ // Sound was looping for n-times: sounds.get(entry.getKey()).getAudioClip().loop(entry.getValue()); } else if (entry.getValue() < 0){ // Sound was looping forever: sounds.get(entry.getKey()).getAudioClip().loop(-1); } else sounds.get(entry.getKey()).getAudioClip().start(); } }
4
@Override public Set<Class<?>> getClasses() { Set<Class<?>> classes = new HashSet<Class<?>>(); classes.add(RouteRestService.class); //:::::::::::::::::::::::::::::::: //:: Setting the Property classes //:::::::::::::::::::::::::::::::: DBProperties.setProperties(); RouteProperties.setProperties(); AdminProperties.setProperties(); return classes; }
3
static public String ParseSrcPos() { if (str.charAt(0) != '(' || str.charAt(str.length() - 1) != ')') { return null; } if (str.length() >= 3) { String srcpos = str.subSequence(1, 4).toString(); if (ParsePosition.IsPos(srcpos)) { str = str.subSequence(4, str.length()).toString(); return srcpos; } } if (str.length() >= 2) { String srcpos = str.subSequence(1, 3).toString(); if (ParsePosition.IsPos(srcpos)) { str = str.subSequence(3, str.length()).toString(); return srcpos; } } return null; }
6
public boolean hasNoJumps() { return successors.size() == 0 && predecessors.size() == 0; }
1
public void fusionLayers() { if (fusionArea.isEmpty()) { return; } mergeOpacityBuffer(curColor, false); fusion.clear(fusionArea, 0x00ffffff); boolean fullAlpha = true, first = true; for (CPLayer l : layers) { if (!first) { fullAlpha = fullAlpha && fusion.hasAlpha(fusionArea); } if (l.visible) { first = false; if (fullAlpha) { l.fusionWithFullAlpha(fusion, fusionArea); } else { l.fusionWith(fusion, fusionArea); } } } fusionArea.makeEmpty(); }
6
public final void listaDeTipos() throws RecognitionException { try { // fontes/g/CanecaSemantico.g:339:2: ( ^( TIPOS_ ( tipo )* ) ) // fontes/g/CanecaSemantico.g:339:4: ^( TIPOS_ ( tipo )* ) { match(input,TIPOS_,FOLLOW_TIPOS__in_listaDeTipos1125); if (state.failed) return ; if ( input.LA(1)==Token.DOWN ) { match(input, Token.DOWN, null); if (state.failed) return ; // fontes/g/CanecaSemantico.g:339:13: ( tipo )* loop21: do { int alt21=2; int LA21_0 = input.LA(1); if ( (LA21_0==TIPO_) ) { alt21=1; } switch (alt21) { case 1 : // fontes/g/CanecaSemantico.g:339:14: tipo { pushFollow(FOLLOW_tipo_in_listaDeTipos1128); tipo(); state._fsp--; if (state.failed) return ; } break; default : break loop21; } } while (true); match(input, Token.UP, null); if (state.failed) return ; } } } catch (RecognitionException erro) { throw erro; } finally { // do for sure before leaving } return ; }
9
public String[] parseMessage(Message msg){ return msg.getContent().split(":"); }
0