text
stringlengths
14
410k
label
int32
0
9
@Override public void postUpdate() { if(!underTrap){ xPos = 12*Math.cos((direction-90.0)/180*Math.PI); yPos = 12*Math.sin((direction-90.0)/180*Math.PI); if(onBattle && canon.getId()==2){ listElements.addElement(new Bullet(x-xPos,y-yPos, direction)); } if(onBattle && canon.getId()==6){ listElements.addElement(new Bullet(x+xPos,y+yPos, direction)); } // TODO Auto-generated method stub } else { onBattle=false; if(timerTrap>0)timerTrap--; else underTrap=false; } }
6
public ParseException generateParseException() { jj_expentries.clear(); boolean[] la1tokens = new boolean[54]; if (jj_kind >= 0) { la1tokens[jj_kind] = true; jj_kind = -1; } for (int i = 0; i < 28; i++) { if (jj_la1[i] == jj_gen) { for (int j = 0; j < 32; j++) { if ((jj_la1_0[i] & (1<<j)) != 0) { la1tokens[j] = true; } if ((jj_la1_1[i] & (1<<j)) != 0) { la1tokens[32+j] = true; } } } } for (int i = 0; i < 54; i++) { if (la1tokens[i]) { jj_expentry = new int[1]; jj_expentry[0] = i; jj_expentries.add(jj_expentry); } } int[][] exptokseq = new int[jj_expentries.size()][]; for (int i = 0; i < jj_expentries.size(); i++) { exptokseq[i] = jj_expentries.get(i); } return new ParseException(token, exptokseq, tokenImage); }
9
public Dungeon(Point location) { this.location = location; active = false; random = new Random(); max_floors = random.nextInt(10) + 5;//max 15 min 5 size = 100; floor = 0; floors = new ArrayList<DungeonFloor>(); for (int c = 0; c < max_floors; c++) { floors.add(new DungeonFloor(size, 0)); } floors.get(floor).makeActive(); floors.get(floor).playerEnter(); GlobalGame.game.player.dungeon_position = floors.get(floor).getPlayerPosition();//TODO another terrible workaround }
1
public static void rejectFriendRequest(int senderID, int receiverID) { try { String statement = new String("UPDATE " + DBTable + " SET isRejected = true " + "WHERE uid1 = ? and uid2 = ? and isConfirmed = false and isRejected = false"); PreparedStatement stmt = DBConnection.con.prepareStatement(statement); stmt.setInt(1, senderID); stmt.setInt(2, receiverID); DBConnection.DBUpdate(stmt); } catch (SQLException e1) { e1.printStackTrace(); } }
1
private void gameSetup() { // BUILD THE BOARD mother.setBounds(0, 0, WIDTH, HEIGHT-30); GridLayout gl = new GridLayout(11, 11); board = new JPanel(gl); board.setBounds(0, 0, WIDTH, HEIGHT-30); // Add all spaces to the board int topPos = 20; int leftPos = 19; int rightPos = 31; int botPos = 9; for(int i = 1; i <= 121; i++) { // All spaces on top if(i <= 11) { Space s = spaces.get(topPos++); s.setBorder(BorderFactory.createLineBorder(Color.WHITE)); board.add(s); } // All spaces on left else if(i % 11 == 1) { Space s = spaces.get(leftPos--); s.setBorder(BorderFactory.createLineBorder(Color.WHITE)); board.add(s); } // All spaces on right else if(i % 11 == 0 && i != 121) { Space s = spaces.get(rightPos++); s.setBorder(BorderFactory.createLineBorder(Color.WHITE)); board.add(s); } // All spaces on bottom else if(i > 111 && i <= 121) { Space s = spaces.get(botPos--); s.setBorder(BorderFactory.createLineBorder(Color.WHITE)); board.add(s); } else { JPanel jp = new JPanel(new GridBagLayout()); board.add(jp); } } mother.add(board, new Integer(0), 0); add(mother); pack(); setMinimumSize(new Dimension(WIDTH, HEIGHT)); getContentPane().setBackground(Color.BLACK); setResizable(false); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }
7
public String print() { String output = "Empty Shape"; if( PointList != null ) { output = "Shape - " + PointList.size() + "Points"; for( Point n: PointList ) { output = output + n.print(); } } return output; }
2
private String queryResultsToXMLStringInternal(CycObject query, CycObject mt, InferenceParameters queryProperties, CycList xmlSpec) throws UnknownHostException, IOException, CycApiException { String xmlSpecString = (xmlSpec == null) ? ":default" : xmlSpec.stringApiValue(); final String script = "(query-results-to-xml-string " + query.stringApiValue() + " " + makeELMt(mt).stringApiValue() + " " + queryPropertiesToString(queryProperties) + " " + xmlSpecString + ")"; return converseString(script); }
1
public static void moveUpText(OutlinerCellRendererImpl textArea, JoeTree tree, OutlineLayoutManager layout) { Node currentNode = textArea.node; // Get Prev Node Node prevNode = tree.getPrevNode(currentNode); if (prevNode == null) { return; } // Record the EditingNode and CursorPosition tree.setEditingNode(prevNode); tree.setCursorPosition(OutlinerDocument.findNearestCaretPosition(textArea.getCaretPosition(), tree.getDocument().getPreferredCaretPosition(), prevNode)); // Clear Text Selection textArea.setCaretPosition(0); textArea.moveCaretPosition(0); // Freeze Undo Editing UndoableEdit.freezeUndoEdit(currentNode); // Redraw and Set Focus if (prevNode.isVisible()) { layout.setFocus(prevNode,OutlineLayoutManager.TEXT); } else { layout.draw(prevNode,OutlineLayoutManager.TEXT); } }
2
public void shiftRight(boolean isJump){ reDrawIndex += 5; if(reDrawIndex > files.size()-1){ reDrawIndex = reDrawIndex - files.size(); } if(isJump){ listPosition += 5; if(listPosition > files.size()-1){ listPosition = listPosition - files.size(); } } }
3
public void draw(Graphics g){ if(pDir == 0){ if(HUD.inventory[0].getItemNum() != 0) g.drawImage(HUD.inventory[0].getPicDown(), playerRect.x+15-HUD.inventory[0].width-1, playerRect.y+15-2, null); g.drawImage(monkDown, playerRect.x, playerRect.y, null); } if(pDir == 1){ if(HUD.inventory[0].getItemNum() != 0) g.drawImage(HUD.inventory[0].getPicUp(), playerRect.x+HUD.inventory[0].width/2-1, playerRect.y-HUD.inventory[0].height+2, null); g.drawImage(monkUp, playerRect.x, playerRect.y, null); } if(pDir == 2){ if(HUD.inventory[0].getItemNum() != 0) g.drawImage(HUD.inventory[0].getPicLeft(), playerRect.x-HUD.inventory[0].height+2, playerRect.y+15-HUD.inventory[0].width-1, null); g.drawImage(monkLeft, playerRect.x, playerRect.y, null); } if(pDir == 3){ if(HUD.inventory[0].getItemNum() != 0) g.drawImage(HUD.inventory[0].getPicRight(), playerRect.x+15-2, playerRect.y+1, null); g.drawImage(monkRight, playerRect.x, playerRect.y, null); } }
8
protected void updateModelForces(float deltaTime) { boolean wasIntersection = true; for (int n = 0; wasIntersection & n <= 5; n++) { n++; wasIntersection = false; for (int i = 0; i < models.size() - 1; i++) for (int j = i + 1; j < models.size(); j++) { if (wasIntersection) models.get(i).crossThem(models.get(j), deltaTime); else wasIntersection = models.get(i).crossThem(models.get(j), deltaTime); } } for (int i = 0; i < models.size() - 1; i++) for (int j = i + 1; j < models.size(); j++) { models.get(i).updateStaticForces(models.get(j), deltaTime); } }
6
public void hit(ArrayList<Tank> tanks){ for(Tank tank:tanks){ if(tank.inside(this) && tank.getId()!=id && tank.isAlive() ){ this.setAlive(false); } } }
4
public void mutate(double lineProb, Random rand) { for (ArrayList<WorkUnit> personWorkList : personWorkLists) { if (rand.nextDouble() < lineProb) { int indexA = rand.nextInt(projectSize); int indexB = rand.nextInt(projectSize); if (indexA == indexB) { if (indexB == projectSize - 1) indexB--; else indexB++; } WorkUnit temp = personWorkList.get(indexA); personWorkList.set(indexA, personWorkList.get(indexB)); personWorkList.set(indexB, temp); } } }
4
public String whichBinary(String type) { for (int i = 0; i < Expression.binaryTypes.length; i++) { if (type.equals (Expression.binaryTypes[i])) { if(type.equals("plus")||type.equals("minus")||type.equals("times") ||type.equals("divided by")) { return "operator"; } else if(type.equals("or")||type.equals("and")) { return "logic"; } else { //"equals", "greater than", "less than" return "compare"; } } } return null; }
8
protected Nodo reducirArbol(int dato) { if(super.raiz.getOpt1() != null) { if(super.raiz.getOpt1().getDato() == dato) return super.raiz.getOpt1(); } if(super.raiz.getOpt2() != null) { if(super.raiz.getOpt2().getDato() == dato) return super.raiz.getOpt2(); } if(super.raiz.getOpt3() != null) { if(super.raiz.getOpt3().getDato() == dato) return super.raiz.getOpt3(); } if(super.raiz.getOpt4() != null) { if(super.raiz.getOpt4().getDato() == dato) return super.raiz.getOpt4(); } return null; }
8
public void handleInput() { if((InputHandler.isPressed(InputHandler.W)) && (currentOption > 0)) { currentOption--; } else if((InputHandler.isPressed(InputHandler.S)) && currentOption < options.length - 1) { currentOption++; } else if(InputHandler.isPressed(InputHandler.SPACE)) { select(); } }
5
public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (true) { System.out.println("Please enter 3 numbers"); int first = sc.nextInt(); int second = sc.nextInt(); int third = sc.nextInt(); if (first == 0 && second == 0 && third == 0) { break; } if ((first + second + third) % 3 == 0) { System.out.println("Yes"); } else { System.out.println("No"); } } }
5
public void setupContent() { /* * Other stuff Being created here */ JPanel empty = new JPanel(); empty.setBorder(new EmptyBorder(0, 0, 20, 0)); empty.setOpaque(false); JPanel info = new JPanel(); info.add(statusLabel); info.setBorder(new EmptyBorder(0, 0, 10, 0)); info.setOpaque(false); JLabel background = new JLabel(new ImageIcon(getClass().getResource( "resources/slotMachine2.png"))); GridBagConstraints gbc_background = new GridBagConstraints(); gbc_background.gridx = 0; gbc_background.gridy = 0; gbc_background.gridwidth = 0; gbc_background.gridheight = 4; GridBagConstraints gbc_info = new GridBagConstraints(); gbc_info.gridx = 0; gbc_info.gridy = 0; GridBagConstraints gbc_empty = new GridBagConstraints(); gbc_empty.gridx = 0; gbc_empty.gridy = 1; GridBagConstraints gbc_wheel = new GridBagConstraints(); gbc_wheel.gridx = 0; gbc_wheel.gridy = 2; getContentPane().add(info, gbc_info); /* * Below is the bet and spin button which will prompt for a bet and then * spin if the bet is less than 0 or greater than the user's total money * then it'll have the user bet again. If the user has no money then it * will tell them as well. */ JButton spinButton = new JButton(); spinButton.setBackground(Color.ORANGE); spinButton.setText("Bet and Spin"); spinButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String inputValue = JOptionPane .showInputDialog("How much would you like to bet?"); if (totalMoney < 0.01) { JOptionPane .showMessageDialog(null, "You Are Broke Come Back Later When You Have Money!"); } else { float bet = Float.parseFloat(inputValue); while (bet <= 0 || bet > totalMoney) { inputValue = JOptionPane .showInputDialog("Illegal bet, please bet again"); bet = Float.parseFloat(inputValue); } bet = Float.parseFloat(inputValue); totalMoney -= bet; machine.turnAll(bet); totalMoney += machine.getMoneyWon(); statusLabel.setText("Total Money: " + totalMoney); machine.revalidate(); machine.repaint(); } } }); // --------------------- info.add(spinButton); getContentPane().add(empty, gbc_empty); getContentPane().add(machine, gbc_wheel); JButton quit = new JButton("Quit Game"); quit.setBackground(Color.ORANGE); quit.addActionListener(this); GridBagConstraints gbc_quit = new GridBagConstraints(); gbc_quit.gridx = 0; gbc_quit.gridy = 3; getContentPane().add(quit, gbc_quit); getContentPane().add(background, gbc_background); }
3
@Override public String getMessageFromTest() { if (isCorrectSoFar) { return SUCCESS_STRING; } else { final String errorString = expectedProgramBehaviorCopy.getErrorString(); if ("".equals(errorString)) { throw new IllegalStateException("message from test is empty; almost certainly getMessageFromTest was called before running any test."); } return errorString; } }
2
public String getSourceFile() { SourceFileAttribute sf = (SourceFileAttribute)getAttribute(SourceFileAttribute.tag); if (sf == null) return null; else return sf.getFileName(); }
1
public static byte[] getBytes(Object o) { if (o instanceof String) { return ((String)o).getBytes(); } else if (o instanceof byte[]) { return (byte[])o; } else if (o instanceof Serializable) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutput out = null; try { out = new ObjectOutputStream(bos); out.writeObject(o); byte[] bytes = bos.toByteArray(); return bytes; } catch(Exception e) { return null; } finally { try { if (out != null) { out.close(); } } catch (IOException ex) { // ignore close exception } try { bos.close(); } catch (IOException ex) { // ignore close exception } } } throw new RuntimeException("Fail to convert object to bytes"); }
7
private void updateStates() { State aux; for (State m : successors) { aux = states.get(m.puzzle.getKey()); if (aux != null) { if (aux.opened) { if (m.getStartDistance() < aux.getStartDistance()) { openedStates.remove(aux); aux.setTotalDistance(m.getStartDistance(), m.getFinalDistance()); aux.father = m.father; m.opened = true; openedStates.add(m); } } else { if (m.getStartDistance() < aux.getStartDistance()) { aux.setTotalDistance(m.getStartDistance(), m.getFinalDistance()); aux.father = m.father; aux.opened = true; } openedStates.add(aux); } } else { m.opened = true; openedStates.add(m); states.put(m.puzzle.getKey(), m); } } }
5
public ListNode reverseBetween2(ListNode head, int m, int n) { // Note: The Solution object is instantiated only once and is reused by each test case. if ( m == n || n == 1){ return head; } ListNode tmpHead = new ListNode(0); tmpHead.next = head; ListNode tmp = head; int i = 1; for (; i < m; ++i){ tmpHead = tmpHead.next; tmp = tmp.next; } for (;i < n; ++i){ ListNode tmpBack = tmp.next; tmp.next = tmpBack.next; tmpBack.next = tmpHead.next; tmpHead.next = tmpBack; } return m == 1? tmpHead.next : head; }
5
public void patientPersonalInfo(PatientInfo patient, JTextField[] tfPatient, JTextPane tp, JTextPane[] patientTP) { StringBuffer info = new StringBuffer(); if (tp == null && patientTP == null) { tfPatient[2].setText(patient.getBdate().toString()); tfPatient[3].setText(patient.getSsn().substring(0, 3) + "-" + patient.getSsn().substring(3, 6) + "-" + patient.getSsn().substring(6, 9)); tfPatient[4].setText(patient.getEmail()); tfPatient[5].setText(patient.getAddress()); tfPatient[6].setText(patient.getZip()); tfPatient[7].setText(patient.getPhone()); tfPatient[8].setText(patient.getMedcard()); tfPatient[9].setText(patient.getInsurrance()); } if (tfPatient == null && patientTP == null) { info.append("<table>"); info.append("<tr><td>Patient: <b>"); info.append(patient.getLname()); info.append(", " + patient.getFname()); info.append("</b></td></tr>"); info.append("<tr><td>Phone: <b>"); info.append(patient.getPhone() + "</b></td></tr>"); info.append("<tr><td>Address: <b>"); info.append(patient.getAddress() + ", " + patient.getZip() + "</b></td></tr>"); info.append("<tr><td>Med card: <b>"); info.append(patient.getMedcard() + "</b></td></tr>"); info.append("<tr><td>Insurance: <b>"); info.append(patient.getInsurrance() + "</b></td></tr>"); info.append("<tr><td>SSN: <b>"); info.append(patient.getSsn() + "</b></td></tr>"); info.append("<tr><td>E-mail: <b>"); info.append(patient.getEmail() + "</b></td></tr>"); info.append("</table>"); tp.setText(info.toString()); } if (tfPatient == null && tp == null) { if (patient.getGmedhistory() != null) { patientTP[0].setText("<b><span style='font-size: 16pt'>" + patient.getGmedhistory() + "</span></b><br /><br />"); } if (patient.getIllnesshistory() != null) { patientTP[1].setText("<b><span style='font-size: 16pt'>" + patient.getIllnesshistory() + "</span></b><br /><br />"); } if (patient.getMedspechistory() != null) { patientTP[2].setText("<b><span style='font-size: 16pt'>" + patient.getMedspechistory() + "</span></b><br /><br />"); } } }
9
public int LCAutil(Node node,int a,int b){ if(node == null){ System.out.println("root is coming as null"); return -1; } if( (node.value >= a && node.value <= b ) ){ if( findNodes(node, a) && findNodes(node, b) ){ return node.value; } else{ return -1; } } if(node.value > a && node.value > b){ System.out.println("traverse left"); return LCA(node.left,a,b); }else{ System.out.println("traverse right"); return LCA(node.right,a,b); } }
7
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { FullHttpResponse response; String requestUri; if (msg instanceof HttpRequest) { HttpRequest req = (HttpRequest) msg; boolean keepAlive = isKeepAlive(req); requestUri = req.getUri().toLowerCase(); ServerRequest serverRequest = new ServerRequest( ((InetSocketAddress) ctx.channel().remoteAddress()) .getHostString()); dao.mergeServerRequest(serverRequest); if (is100ContinueExpected(req)) { ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE)); } switch (requestUri) { case HELLO: content = Unpooled.unreleasableBuffer(Unpooled.copiedBuffer( "Hello World!", CharsetUtil.UTF_8)); response = new DefaultFullHttpResponse(HTTP_1_1, OK, content.duplicate()); timer.newTimeout(new HelloWorldTimerTask(ctx, response, keepAlive), 10, TimeUnit.SECONDS); return; case STATUS: content = Unpooled.unreleasableBuffer(Unpooled.copiedBuffer( generateStatus(), CharsetUtil.UTF_8)); response = new DefaultFullHttpResponse(HTTP_1_1, OK, content.duplicate()); writeToResponse(ctx, response, keepAlive); return; default: if (requestUri.matches(REDIRECT_REGEXP)) { QueryStringDecoder qsd = new QueryStringDecoder(requestUri); List<String> redirectUrl = qsd.parameters().get("url"); response = new DefaultFullHttpResponse(HTTP_1_1, FOUND); response.headers().set(LOCATION, redirectUrl); dao.mergeRedirect(new Redirect( redirectUrl.get(0), 1)); } else { response = new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN); } writeToResponse(ctx, response, keepAlive); } } }
5
private static boolean reachableFromSource(Vertex from, HashMap<Vertex, Vertex> predecessors) { HashSet<Vertex> visited = new HashSet<Vertex>(); Vertex source = new Vertex(0, 0); Vertex aVertex = new Vertex(from.posX, from.posY); Vertex me; boolean exit = false; while(predecessors.get(aVertex) != null && !exit) { me = new Vertex(aVertex.posX, aVertex.posY); aVertex = predecessors.get(aVertex); if(aVertex.equals(source) || me.equals(aVertex)) { exit = true; } if(visited.contains(aVertex)) { exit = true; } else { visited.add(aVertex); } } return aVertex.equals(source); }
5
@Override public void onEnable() { Mc_IrcBotCommands irccommands = new Mc_IrcBotCommands(this); Mc_PlayerCommands playercommands = new Mc_PlayerCommands(this); getCommand("ircbot").setExecutor(irccommands); getCommand("irc").setExecutor(playercommands); IrcPlayerListener listener = new IrcPlayerListener(this); SettingsUtils.ReadMessageTypes_Properties(); if(SettingsUtils.ReadIrc_Properties() == false) { Utils.Warning("Some required values in irc.properties were missing."); } else if(SettingsUtils.getIfDefaultClient()) { Utils.Info("Initializing default client..."); SettingsUtils.InitializeDefaultClient(this); try { Utils.Info("Connecting to server..."); if(SettingsUtils.getAutoConnect() == true) { Manager.getCurrentClient().Connect(); Manager.getCurrentClient().Login(); Manager.getCurrentClient().Listen(); } } catch(Exception e) { Utils.LogException(e, "connecting default client"); } } Utils.Info("Version " + this.getDescription().getVersion() + " enabled."); }
4
public void gameAssists() { Collections.shuffle(assists); for (int i = 0; i < 20; i++) { Collections.shuffle(assists); if(assists.get(0) == team.get(0).name) { astC++; } if(assists.get(0) == team.get(1).name) { astPF++; } if(assists.get(0) == team.get(2).name) { astSF++; } if(assists.get(0) == team.get(3).name) { astSG++; } if(assists.get(0) == team.get(4).name) { astPG++; } } }
6
private static List<String> tokenize(String bencodedString) throws DecoderException { List<String> tokenList = new ArrayList<String>(); Matcher m = DECODE_PATTERN.matcher(bencodedString); while(m.find()) { String extractedToken = bencodedString.substring(m.start(), m.end()); if(extractedToken.equals(BencodingToken.START_TOKEN)) { m.find(); tokenList.add(BencodingToken.START_TOKEN); tokenList.add(bencodedString.substring(m.start(), m.end())); m.find(); if(!bencodedString.substring(m.start(), m.end()).equals(BencodingToken.END_TOKEN)) { throw new DecoderException(); } } if(extractedToken.contains(BencodingToken.COLON_TOKEN)) { int stringLength = Integer.parseInt(extractedToken.substring(0, extractedToken.length()-1)); String stringToken = bencodedString.substring(m.end(), m.end() + stringLength); tokenList.add(BencodingToken.STRING_TOKEN); tokenList.add(stringToken); m = m.region(m.end()+stringLength, bencodedString.length()); } if(extractedToken.equals(BencodingToken.START_LIST_TOKEN)) { tokenList.add(BencodingToken.START_LIST_TOKEN); } if(extractedToken.equals(BencodingToken.START_DICT_TOKEN)) { tokenList.add(BencodingToken.START_DICT_TOKEN); } if(extractedToken.equals(BencodingToken.END_TOKEN)) { tokenList.add(BencodingToken.END_TOKEN); } } return tokenList; }
7
public void movePlayer(String direction){ if (direction.equals("up")){ if (canMove(direction)){ location = location - size; } } else if (direction.equals("down")){ if (canMove(direction)){ location = location + size; } }else if (direction.equals("left")){ if (canMove(direction)){ location = location - 1; } }else if (direction.equals("right")){ if (canMove(direction)){ location = location + 1; } } }
8
public static boolean isWhiteSpaceChar( char tc ) { if( tc == '\u0009' || tc == '\r' || tc == '\n' || tc == '\u000b' || tc == '\u000c' || tc == '\u0000' || tc == '\u00a0' || tc == ' ' ) { return true; } else { return false; } }
8
public static int[] plusOne(int[] digits) { int[] res = new int[digits.length + 1]; boolean isin = false; for (int i = digits.length - 1; i >= 0; i--) { int t = 0; if (i == digits.length - 1 || isin) t = digits[i] + 1; else t = digits[i]; res[i + 1] = t % 10; if (0 == t / 10) isin = false; else isin = true; } if (isin) { res[0] = 1; return res; } else { return Arrays.copyOfRange(res, 1, digits.length + 1); } }
5
private Level findCorrespondingLevel(String levelName, SortedSet<Level> levels) throws CorrespondingLevelNotExistsException { if (null == levelName || "".equals(levelName)) { throw new CorrespondingLevelNotExistsException(); } for (Level level : levels) { if (levelName.equals(level.getName())) { return level; } } throw new CorrespondingLevelNotExistsException(); }
4
public static void startupPropagate() { { Object old$Module$000 = Stella.$MODULE$.get(); Object old$Context$000 = Stella.$CONTEXT$.get(); try { Native.setSpecial(Stella.$MODULE$, Stella.getStellaModule("/LOGIC", Stella.$STARTUP_TIME_PHASE$ > 1)); Native.setSpecial(Stella.$CONTEXT$, ((Module)(Stella.$MODULE$.get()))); if (Stella.currentStartupTimePhaseP(2)) { _StartupPropagate.helpStartupPropagate1(); } if (Stella.currentStartupTimePhaseP(4)) { Logic.$FILLINGCONSTRAINTPROPAGATIONQUEUESp$.setDefaultValue(new Boolean(false)); Logic.$DEFERINGDEFAULTFORWARDINFERENCESp$.setDefaultValue(new Boolean(false)); Logic.$COLLECTFORWARDPROPOSITIONS$.setDefaultValue(null); Logic.$CLASH_EXCEPTIONS$ = List.newList(); } if (Stella.currentStartupTimePhaseP(5)) { { Stella_Class renamed_Class = Stella.defineClassFromStringifiedSource("PROPAGATION-ENVIRONMENT", "(DEFCLASS PROPAGATION-ENVIRONMENT (STANDARD-OBJECT) :SLOTS ((EVALUATION-QUEUE :TYPE (LIST OF PROPOSITION) :INITIALLY (LIST)) (EVALUATION-STATES :TYPE (KEY-VALUE-MAP OF PROPOSITION KEYWORD) :INITIALLY (NEW KEY-VALUE-MAP)) (FORWARD-CHAINING-QUEUE :TYPE (LIST OF PROPOSITION) :INITIALLY (LIST)) (FORWARD-CHAINING-SET :TYPE (HASH-SET OF PROPOSITION PROPOSITION) :INITIALLY (NEW HASH-SET)) (DEFERRED-DEFAULT-PROPOSITIONS :TYPE (LIST OF PROPOSITION) :INITIALLY (LIST)) (ELABORATED-OBJECTS :TYPE HASH-SET :INITIALLY (NEW HASH-SET))))"); renamed_Class.classConstructorCode = Native.find_java_method("edu.isi.powerloom.logic.PropagationEnvironment", "newPropagationEnvironment", new java.lang.Class [] {}); renamed_Class.classSlotAccessorCode = Native.find_java_method("edu.isi.powerloom.logic.PropagationEnvironment", "accessPropagationEnvironmentSlotValue", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.PropagationEnvironment"), Native.find_java_class("edu.isi.stella.Symbol"), Native.find_java_class("edu.isi.stella.Stella_Object"), java.lang.Boolean.TYPE}); } } if (Stella.currentStartupTimePhaseP(6)) { Stella.finalizeClasses(); } if (Stella.currentStartupTimePhaseP(7)) { _StartupPropagate.helpStartupPropagate2(); } if (Stella.currentStartupTimePhaseP(8)) { Stella.finalizeSlots(); Stella.cleanupUnfinalizedClasses(); } if (Stella.currentStartupTimePhaseP(9)) { Stella_Object.inModule(((StringWrapper)(Stella_Object.copyConsTree(StringWrapper.wrapString("LOGIC"))))); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *FILLINGCONSTRAINTPROPAGATIONQUEUES?* BOOLEAN FALSE :DOCUMENTATION \"True if we are inside of 'react-to-kb-update'.\")"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *DEFERINGDEFAULTFORWARDINFERENCES?* BOOLEAN FALSE :DOCUMENTATION \"True if we are propagating strict inferences, and\nposting derived default propositions to temporary queues.\")"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *COLLECTFORWARDPROPOSITIONS* (CONS OF PROPOSITION) NULL :DOCUMENTATION \"Collect goes-true propositions produced by forward\nchaining.\")"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *MAX-SKOLEM-GENERATION-COUNT* INTEGER 3)"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *JUST-IN-TIME-FORWARD-INFERENCE?* BOOLEAN TRUE :PUBLIC? TRUE :DOCUMENTATION \"If TRUE, ensures that forward propagation has\nbeen applied to each instance 'touched' during a query.\")"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *CLASH-EXCEPTIONS* (LIST OF EXCEPTION-RECORD) (NEW LIST) :PUBLIC? TRUE :DOCUMENTATION \"Collects clash exceptions that occur during inference.\")"); HookList.addHook(Stella.$DESTROY_CONTEXT_HOOKS$, Logic.SYM_LOGIC_CULL_CLASH_EXCEPTIONS); } } finally { Stella.$CONTEXT$.set(old$Context$000); Stella.$MODULE$.set(old$Module$000); } } }
7
public static void readFile(String filePath) throws Exception { instructionString = new ArrayList<String>(); try { BufferedReader inputf = new BufferedReader(new FileReader(filePath)); String tmp = null; while ((tmp = inputf.readLine()) != null) { tmp = tmp.trim(); instructionString.add(tmp); } inputf.close(); } catch (IOException io) { System.out.println("File not found. Please provide a valid filePath."); } }
2
public Room getReleaseRoom(Law laws, Area myArea, MOB criminal, LegalWarrant W) { Room room=null; if((criminal.isMonster())&&(criminal.getStartRoom()!=null)) room=criminal.getStartRoom(); else { if((laws.releaseRooms().size()==0)||(laws.releaseRooms().get(0).equals("@"))) return myArea.getMetroMap().nextElement(); if(criminal.location()!=null) room=getRoom(criminal.location().getArea(),laws.releaseRooms()); if(room==null) room=getRoom(myArea,laws.releaseRooms()); if(room==null) room=findTheJudge(laws,myArea); if(room==null) room=myArea.getMetroMap().nextElement(); } return room; }
8
public static boolean readBoolean(String label) { String line = null; boolean finished = false; boolean ret = false; BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); try { while(!finished) { System.out.print(label+" [j/n]: "); line = stdin.readLine().toLowerCase(); if(line.equals("j") || line.equals("ja")) { ret = true; finished = true; } else if(line.equals("n") || line.equals("nein")) { ret = false; finished = true; } else { System.err.println("Bitte geben Sie ja oder nein bzw. j oder n ein!"); } } } catch (IOException e) { e.printStackTrace(); } return ret; }
6
public static byte[] base64decode(String s) { int delta = s.endsWith("==") ? 2 : s.endsWith("=") ? 1 : 0; byte[] buffer = new byte[s.length() * 3 / 4 - delta]; int mask = 0xFF; int index = 0; for (int i = 0; i < s.length(); i += 4) { int c0 = toInt[s.charAt(i)]; int c1 = toInt[s.charAt(i + 1)]; buffer[index++] = (byte) (((c0 << 2) | (c1 >> 4)) & mask); if (index >= buffer.length) { return buffer; } int c2 = toInt[s.charAt(i + 2)]; buffer[index++] = (byte) (((c1 << 4) | (c2 >> 2)) & mask); if (index >= buffer.length) { return buffer; } int c3 = toInt[s.charAt(i + 3)]; buffer[index++] = (byte) (((c2 << 6) | c3) & mask); } return buffer; }
5
private void physicsInvaders() { Invader invader; invader = invaders[0][0]; if (invader.getX() < 5) { invaderSpeedX = invaderSpeedX * -1; invaderLimit = true; } invader = invaders[COLUMNS - 1][ROWS - 1]; if (invader.getX() + invader.getTexture().getW() > Window.getW() - 5) { invaderSpeedX = invaderSpeedX * -1; invaderLimit = true; } for (int column = 0; column < COLUMNS; column++) { for (int row = 0; row < ROWS; row++) { invader = invaders[column][row]; invader.setX(invader.getX() + invaderSpeedX * App.getFTime()); if (invaderLimit) { if (invader.getY() > Window.getH()) invadersNumber = 0; // Eliminar invader.setY(invader.getY() + invaderSpeedY * App.getFTime()); } } } invaderLimit = false; if (invadersNumber == 0) { startInvaders(); } }
7
public void removeDeadFlyUps() { List<FlyUp> toDelete = new ArrayList<FlyUp>(); for(FlyUp fly:flyups) { if(fly.timeSinceCreation() >= 3300) toDelete.add(fly); } for(FlyUp fly:toDelete) { flyups.remove(fly); } }
3
public void checkGuess(char guess) { if (word.contains(Character.toString(guess))) { for (int i = 0; i < length; i++) { char temp = word.charAt(i); if (temp == guess) { placeholder.set(i, guess); } } } else { wrongLetters.add(guess); } }
3
public void setCsaFechaHora(Date csaFechaHora) { this.csaFechaHora = csaFechaHora; }
0
public String addBinaryII(String a, String b) { StringBuilder sb = new StringBuilder(); int i = a.length() - 1, j = b.length() - 1; int l = 0; while (i >= 0 && j >= 0) { int numa = Character.getNumericValue(a.charAt(i)); int numb = Character.getNumericValue(b.charAt(j)); int sum = numa + numb + l; l = 0; if (sum > 1) { l = 1; sum = sum - 2; } sb.append(sum); i--; j--; } int r = 0; String rString = null; if (i < 0) { r = j; rString = b; } else { r = i; rString = a; } for (; r >= 0; r--) { int sum = Character.getNumericValue(rString.charAt(r)); if (l == 1) { sum = l + Character.getNumericValue(rString.charAt(r)); l = 0; if (sum > 1) { l = 1; sum = sum - 2; } } sb.append(sum); } if (l == 1) { sb.append(1); } sb.reverse(); return sb.toString(); }
8
@Override public boolean queueBuffer( byte[] buffer ) { // Stream buffers can only be queued for streaming sources: if( errorCheck( channelType != SoundSystemConfig.TYPE_STREAMING, "Buffers may only be queued for streaming sources." ) ) return false; //ByteBuffer byteBuffer = ByteBuffer.wrap( buffer, 0, buffer.length ); ByteBuffer byteBuffer = (ByteBuffer) BufferUtils.createByteBuffer( buffer.length ).put( buffer ).flip(); IntBuffer intBuffer = BufferUtils.createIntBuffer( 1 ); AL10.alSourceUnqueueBuffers( ALSource.get( 0 ), intBuffer ); if( checkALError() ) return false; if( AL10.alIsBuffer( intBuffer.get( 0 ) ) ) millisPreviouslyPlayed += millisInBuffer( intBuffer.get( 0 ) ); checkALError(); AL10.alBufferData( intBuffer.get(0), ALformat, byteBuffer, sampleRate ); if( checkALError() ) return false; AL10.alSourceQueueBuffers( ALSource.get( 0 ), intBuffer ); if( checkALError() ) return false; return true; }
5
public static Stella_Object accessInputFileStreamSlotValue(InputFileStream self, Symbol slotname, Stella_Object value, boolean setvalueP) { if (slotname == Stella.SYM_STELLA_FILENAME) { if (setvalueP) { self.filename = ((StringWrapper)(value)).wrapperValue; } else { value = StringWrapper.wrapString(self.filename); } } else if (slotname == Stella.SYM_STELLA_IF_NOT_EXISTS_ACTION) { if (setvalueP) { self.ifNotExistsAction = ((Keyword)(value)); } else { value = self.ifNotExistsAction; } } else if (slotname == Stella.SYM_STELLA_BUFFERING_SCHEME) { if (setvalueP) { self.bufferingScheme = ((Keyword)(value)); } else { value = self.bufferingScheme; } } else { { OutputStringStream stream000 = OutputStringStream.newOutputStringStream(); stream000.nativeStream.print("`" + slotname + "' is not a valid case option"); throw ((StellaException)(StellaException.newStellaException(stream000.theStringReader()).fillInStackTrace())); } } return (value); }
6
public Forecasts getForecast() { try { crs = qb.selectFrom("forecast").where("msg_type", "=", "forecast").executeQuery(); while(crs.next()){ String date = crs.getString("day"); String temperature = crs.getString("temperature"); String weatherDescription = crs.getString("summary"); forecasts.forecasts.add(new Forecast(date, temperature, weatherDescription)); } } catch (SQLException e) { e.printStackTrace(); } finally { try { crs.close(); } catch (SQLException e) { e.printStackTrace(); } } return forecasts; }
3
@Override public String getPropertyValues() { String var; if(Math.abs(variance) < EPS) var = ""; else var = " (var=" +variance +")"; if(min != UNDEFINED) { if(max != UNDEFINED) { if(min == max) { return min +getUnit() +var; } else { return "[" +min +", " +max +"]" +getUnit() +var; } } else { return "min " +min +getUnit() +var; } } else { if(max != UNDEFINED) { return "max " +max +getUnit() +var; } else { return "no restrictions"; } } }
5
private void setControlsEnabled(Boolean enabled) { mainWindowView.getNumberOfPointsTextField().setEnabled(enabled); mainWindowView.getIntegrationMethodsComboBox().setEnabled(enabled); mainWindowView.getAngleComboBox().setEnabled(enabled); mainWindowView.getxMaxTextField().setEnabled(enabled); mainWindowView.getxMinTextField().setEnabled(enabled); mainWindowView.getyMinTextField().setEnabled(enabled); mainWindowView.getyMaxTextField().setEnabled(enabled); mainWindowView.getTimeStepTextField().setEnabled(enabled); mainWindowView.getTimePeriodTextField().setEnabled(enabled); mainWindowView.getPsiTextField().setEnabled(enabled); mainWindowView.getPhiTextField().setEnabled(enabled); mainWindowView.getThetaTextField().setEnabled(enabled); }
0
public String getPassword() { return password; }
0
private void createCurrCity(SessionRequestContent request) { City currCity = (City) request.getSessionAttribute(JSP_CURRENT_CITY); if (currCity == null) { currCity = new City(); currCity.setCountry(new Country()); currCity.setDescription(new Description()); } Integer idCountry = ParamManager.getIntParam(request, JSP_CURR_ID_COUNTRY); currCity.getCountry().setIdCountry(idCountry); currCity.setName(request.getParameter(JSP_CITY_NAME)); currCity.setPicture(request.getParameter(JSP_CITY_PICTURE)); currCity.getDescription().setText(request.getParameter(JSP_DESCRIPTION_TEXT)); request.setSessionAttribute(JSP_CURRENT_CITY, currCity); }
1
public void push(PriorityItem o) { LinkedList.Node p = (LinkedList.Node)l.getFirstNode(); if(p == null) { l.add(o); return; } while(((PriorityItem)p.value).compareTo(o) < 0 && p.next != null) { p = p.next; } l.addAfter(o, p); }
3
public static int[] getArr(int n){ int [] array = new int[n]; Random random = new Random(); System.out.println("*******************unsort array NO:"+n+"************"); for(int i =0; i < n;i++){ array[i] = random.nextInt(100); System.out.print(array[i]+" "); } System.out.println(); return array; }
1
public boolean isJoinable(String channel) { this.channel = channel; if (ChannelsConfig.getChannels().getBoolean("channels." + channel + ".joinable") == true) { return true; } else { return false; } }
1
public int getBufferDmg() { int dmgFromBuffers = 0; for (GameAction action: getBuffers()) { dmgFromBuffers += action.getExtraDmg(); } extraDmg = dmgFromBuffers; return dmgFromBuffers; }
1
@Test public void dequeueReturnsObjectsInCorrectOrder() { int[] expected = new int[100]; for (int i = 0; i < expected.length; i++) { expected[i] = i; q.enqueue(i); } int[] actual = new int[100]; for (int i = 0; i < actual.length; i++) { actual[i] = q.dequeue(); } assertArrayEquals(expected, actual); }
2
public void setCueMovto(String cueMovto) { this.cueMovto = cueMovto; }
0
private void txt_num_fileFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txt_num_fileFocusLost System.out.println("a dejado de ser focuseado\n"); if (txt_num_file.getText().length() > 0) { try { boolean existe; existe = TicketDAO.getInstance().existeNumFile(txt_num_file.getText()); if (!existe) { JOptionPane.showMessageDialog(null, "El num file no existe", "No encontrado", JOptionPane.WARNING_MESSAGE); txt_num_file.setText(""); } } catch (SQLException ex) { Logger.getLogger(DetalleRegistro.class.getName()).log(Level.SEVERE, null, ex); } } }//GEN-LAST:event_txt_num_fileFocusLost
3
public void sendData(String data) { if(connected) { try { if(sock.isClosed()) disconnectFromURL(); else if(!sock.isConnected()) disconnectFromURL(); else { final byte[] bytes=Telnet.peruseInput(data); if(bytes!=null) { out.write(bytes); if((bytes.length==0)||((bytes[bytes.length-1]!=13)&&(bytes[bytes.length-1]!=10))) out.writeBytes("\n"); out.flush(); } } } catch(final IOException e) { disconnectFromURL(); } } }
8
public void testChain1() { TreeNode key = new TreeNode("leaf"); TreeNode tree = mkChain(new TreeNode[]{ key }); setTree(tree); Question1 originalTree = ((Question2)answer).tree; try { Map result = synchronizeTree(((Question2)answer).convertTree()); if (result == null) { fail(null, "You returned a `null` map from a leaf node!"); } // end of if-then if (result.size() != 1) { fail(null, "You generated a map (" + toString(result) + ") with " + result.size() + " elements from a leaf node!"); } // end of if-then if (! result.containsKey(originalTree)) { fail(null, "Your map does not contain `this` tree as a key!"); } // end of if-then if (result.get(originalTree) == null) { fail(null, "You generated a map that associates a `null` value with a key!"); } // end of if-then if (! (result.get(originalTree) instanceof TreeNode[])) { if (result.get(originalTree) instanceof TreeNode) { fail(null, "Your keys should **not** be associated with values that have type `TreeNode`!"); } // end of if-then fail(null, "Your keys are associated with values that are not of type `TreeNode[]`!"); } // end of if-then assertTrue(null, "Your code failed to correctly convert a leaf node tree.", ((TreeNode[])(result.get(originalTree))).length == 0); } catch(TreeException exn) { fail(exn, "An unexpected `TreeException` was generated!"); } catch(ClassCastException exn) { fail(exn, "Your `keys` should have type **TreeNode** and your `values` should have type **TreeNode[]**."); } catch(Throwable exn) { fail(exn, "No exception's should be generated, but your code threw: " + exn.getClass().getName()); } // end of try-catch }
9
public String toGetSourceString(OgnlContext context, Object target) { if (target == null) throw new UnsupportedCompilationException("Current target is null, can't compile."); try { Object value = getValueBody(context, target); if (value != null && Boolean.class.isAssignableFrom(value.getClass())) _getterClass = Boolean.TYPE; else if (value != null) _getterClass = value.getClass(); else _getterClass = Boolean.TYPE; // iterate over children to make numeric type detection work properly OgnlRuntime.getChildSource(context, target, _children[0]); OgnlRuntime.getChildSource(context, target, _children[1]); // System.out.println("comparison expression currentType: " + context.getCurrentType() + " previousType: " + context.getPreviousType()); boolean conversion = OgnlRuntime.shouldConvertNumericTypes(context); String result = conversion ? "(" + getComparisonFunction() + "( ($w) (" : "("; result += OgnlRuntime.getChildSource(context, target, _children[0], conversion) + " " + (conversion ? "), ($w) " : getExpressionOperator(0)) + " " + OgnlRuntime.getChildSource(context, target, _children[1], conversion); result += conversion ? ")" : ""; context.setCurrentType(Boolean.TYPE); result += ")"; return result; } catch (NullPointerException e) { // expected to happen in some instances throw new UnsupportedCompilationException("evaluation resulted in null expression."); } catch (Throwable t) { throw OgnlOps.castToRuntime(t); } }
9
public <T extends Component> Collection<T> getAllComponentsOfType( Class<T> componentType) { synchronized (componentStores) { HashMap<UUID, ? extends Component> store = componentStores .get(componentType); if (store == null) { return new LinkedList<>(); } return (Collection<T>) store.values(); } }
2
public String convert(String s, int nRows) { int len = s.length(); if ((nRows==1)||(len<nRows)) return s; int block = nRows*2-2; int nBlock = (len+block-len%block)/block; int[][] location = new int[nRows][nBlock*(nRows-1)]; // reseting the location of each char main: for (int i = 0; i < nBlock; i++) { for (int j = 0; j < block; j++) { int num = i*block+j; if (num >= len) break main; if (j < nRows){ location[j][i*(nRows-1)] = num; } else{ location[2*(nRows-1)-j][i*(nRows-1)+j-nRows+1] = num; } } } // output string StringBuilder builder = new StringBuilder(); builder.append(s.charAt(0)); for (int i = 0; i < nRows; i++) { for (int j = 0; j < nBlock*(nRows-1); j++) { int locOld = location[i][j]; if (locOld!=0){ builder.append(s.charAt(locOld)); } } } return builder.toString(); }
9
public void execute () { Double cyclops = null; try { CycAccess cycAccess = new CycAccess(); System.out.println("Loading benchmarks.lisp"); String script = "(load \"" + benchmarkFilePath + "\")"; cycAccess.converseVoid(script); script = "(benchmark-cyclops)"; System.out.println("Running Cyclops benchmark"); cyclops = (Double) cycAccess.converseObject(script); } catch (Exception e) { System.err.println(e.getMessage()); e.printStackTrace(); System.exit(1); } System.out.println(cyclops + " Cyclops (Cyc Logical Operations Per Second)"); }
1
@Override public void input(float delta) { float movAmt = speed * delta; if (Input.getKey(forwardKey)) move(getTransform().getRot().getForward(), movAmt); if (Input.getKey(backKey)) move(getTransform().getRot().getForward(), -movAmt); if (Input.getKey(leftKey)) move(getTransform().getRot().getLeft(), movAmt); if (Input.getKey(rightKey)) move(getTransform().getRot().getRight(), movAmt); if (Input.getKey(downKey)) move(yAxis, -movAmt); else if (Input.getKey(upKey)) move(yAxis, movAmt); }
6
private void selectRandomNumber() { phr1 = ""; phr2 = ""; int tmp = getRand(nrPhr1_9000); if (tmp != -1) { phr1 += nrPhr1_9000[tmp]; phr1 += conPhr1[2]; phr2 += nrPhr2_9000[tmp]; phr2 += conPhr2[2]; } tmp = getRand(nrPhr1_900); if (tmp != -1) { phr1 += nrPhr1_900[tmp]; phr1 += conPhr1[1]; phr2 += nrPhr2_900[tmp]; phr2 += conPhr2[1]; } if (LangCoach.RANDOM.nextBoolean()) { int teentmp = getRand(nrPhr1_90); int nrtmp = getRand(nrPhr1_9); if (teentmp != -1 && nrtmp != -1) { if (swpPhr1[0].equals("+")) { phr1 += nrPhr1_9[nrtmp]; phr1 += conPhr1[0]; phr1 += nrPhr1_90[teentmp]; } else { phr1 += nrPhr1_90[teentmp]; phr1 += conPhr1[0]; phr1 += nrPhr1_9[nrtmp]; } if (swpPhr2[0].equals("+")) { phr2 += nrPhr2_9[nrtmp]; phr2 += conPhr2[0]; phr2 += nrPhr2_90[teentmp]; } else { phr2 += nrPhr2_90[teentmp]; phr2 += conPhr2[0]; phr2 += nrPhr2_9[nrtmp]; } } } else { tmp = getRand(nrPhr1_19); if (tmp != -1) { phr1 += nrPhr1_19[tmp]; phr1 += conPhr1[0]; phr2 += nrPhr2_19[tmp]; phr2 += conPhr2[0]; } } }
8
public void setCliente(Cliente cliente) { this.cliente = cliente; }
0
public Game(int unit) { this.unit.value = unit; Dimension spielgrenzeSize = new Dimension(FIELD_DIMENSION.width, FIELD_DIMENSION.height); Spielgrenze spielgrenze = new Spielgrenze( new Rectangle(new Point(0, 0), spielgrenzeSize), this.unit); schlange = new SchlangenKopf( new Rectangle( (int)spielgrenze.getX() + 2, (int)spielgrenze.getY() + 2, 1, 1), this.unit, Color.GREEN); gameElements.add(spielgrenze); for (int i = 1; i < Zufallsgenerator.zufallszahl(DIAMONDS_NUMBER_MIN, DIAMONDS_NUMBER_MAX) + 1; i++) { Rectangle diamantRect = new Rectangle( (int)spielgrenze.getX() + Zufallsgenerator.zufallszahl(0, FIELD_DIMENSION.width - 1), (int)spielgrenze.getY() + Zufallsgenerator.zufallszahl(0, FIELD_DIMENSION.height - 1), 1, 1); Diamant newDiamant = new Diamant(diamantRect, this.unit, Zufallsgenerator.zufallszahl(DIAMONDS_POINTS_MIN, DIAMONDS_POINTS_MAX)); gameElements.add(newDiamant); diamanten.add(newDiamant); } gameElements.add(schlange); }
1
public ReferenceList createReferenceList() { return new ReferenceList(); }
0
public int createShader(String filename, int shaderType) throws Exception { int shader = 0; try { shader = ARBShaderObjects.glCreateShaderObjectARB(shaderType); if (shader == 0) return 0; ARBShaderObjects.glShaderSourceARB(shader, readFileAsString(filename)); ARBShaderObjects.glCompileShaderARB(shader); if (ARBShaderObjects.glGetObjectParameteriARB(shader, ARBShaderObjects.GL_OBJECT_COMPILE_STATUS_ARB) == GL11.GL_FALSE) throw new RuntimeException("Error creating shader: " + getLogInfo(shader)); return shader; } catch (Exception exc) { ARBShaderObjects.glDeleteObjectARB(shader); throw exc; } }
3
private void drawLoopLine() { parent.noStroke(); parent.fill(0); parent.rect(controlButtons.get(0).getX() + 40, controlButtons.get(2).getY() + 80, 320, 5); /* ArrayList<Integer> tempTimes = loop.getTimes(); for(LoopNode node : graphedInputs){ float distance = 320.0f * ((float) note / (float)loop.getEndTime()); parent.stroke(0); parent.fill(0,0,100); parent.rect((controlButtons.get(0).getX() + 40) + distance, controlButtons.get(2).getY() + 70, 2, 15); String time = "" + (float)( note / 1000.0f); parent.fill(0); parent.textAlign(PConstants.CENTER); parent.text(time, (controlButtons.get(0).getX() + 40) + distance, controlButtons.get(2).getY() + 97); }u*/ for(LoopNode node : graphedInputs){ node.draw(); } }
1
public static int attemptGetEntryFieldByNumberInput(List<Integer> fieldList, String input) { int intInput; try { intInput = Integer.valueOf(input); } catch (NumberFormatException e) { return -1; } if (intInput > -1 && intInput < fieldList.size()) return intInput; return -1; }
3
private void moveMonth(int numberToMove) { if (DEBUG) log("Beginning moveMonth(int numberToMove) method"); if (DEBUG) log("1. Clone today"); if (DEBUG) log(" Current date: " + date(currentCalendar)); Calendar temp = (Calendar)currentCalendar.clone(); if (DEBUG) log("2. Add " + numberToMove + " month(s) to clone"); temp.add(Calendar.MONTH, numberToMove); if (DEBUG) log("3. Configure Month View using clone"); configureMonthView(temp); if (DEBUG) log("4. Change month label"); if (DEBUG) log(" Started with " + monthHeaderLabel.getText()); monthHeaderLabel.setText(month(currentCalendar.get(Calendar.MONTH)) + " " + currentCalendar.get(Calendar.YEAR)); if (DEBUG) log(" Ended with " + monthHeaderLabel.getText()); monthView.repaint(); }
8
public void Update(GameTime gameTime) { mMenu.Update(); if (!mMenu.IsMenuItemSelected()) { mMenu.SelectMenuItem(new Vector2(mInput.GetMouseX(), GameProperties.WindowHeight() - mInput.GetMouseY())); if (mInput.IsMouseHit(0)) { switch(mMenu.GetSelected()) { case 0: { UnLoad(); } break; case 1: { mMenu.MenuItemSelected(); } break; case 2: { mMenu.MenuItemSelected(); } break; case 3: { mMenu.MenuItemSelected(); } break; case 4: { try { int x = ((IntegerMenuItem)mMenu.GetMenuItem(1)).GetIntValue(); int y = ((IntegerMenuItem)mMenu.GetMenuItem(2)).GetIntValue(); Boolean f = ((BooleanMenuItem)mMenu.GetMenuItem(3)).GetBooleanValue(); GameProperties.HandleCommand("screen_width " + x); GameProperties.HandleCommand("screen_height " + y); GameProperties.HandleCommand("fullscreen " + f); GameProperties.UpdateWindow(); } catch(Exception e) { } } break; } } } }
8
@Override public void update(final int delta) { if (!entitiesToAdd.isEmpty()) { entities.addAll(entitiesToAdd); entitiesToAdd.clear(); } List<Entity> deadEntites = null; for (Entity e : entities) { e.update(delta); if (!e.isAlive()) { if (deadEntites == null) deadEntites = new ArrayList<Entity>(); deadEntites.add(e); } } if (deadEntites != null) entities.removeAll(deadEntites); }
5
private void firstLogin() { boolean flag = true; String tip = "请输入账号"; while(flag) { String input = JOptionPane.showInputDialog(null, tip, "", WIDTH); if(input==null) { if(user_name==null) continue; else break; } if(usermap.containsKey(input)) { user_name = input; account.setText(user_name); break; } InfoDownload info_obj = new InfoDownload(); if(info_obj.init(input)) { user_name = input; info_obj.getinfo(); usermap.put(user_name, 1); account.setText(user_name); flag = false; } else { tip = "账号不存在,请重新输入"; } } }
5
protected void doTestCycAccess9(CycAccess cycAccess) { long startMilliseconds = System.currentTimeMillis(); try { CycConstant brazil = cycAccess.getKnownConstantByGuid(BRAZIL_GUID_STRING); CycConstant country = cycAccess.getKnownConstantByGuid(COUNTRY_GUID_STRING); CycConstant worldGeographyMt = cycAccess.getKnownConstantByGuid( WORLD_GEOGRAPHY_MT_GUID_STRING); CycConstant dog = cycAccess.getKnownConstantByGuid(DOG_GUID_STRING); HashSet hashSet = new HashSet(); hashSet.add(dog); assertTrue(hashSet.contains(dog)); CycConstant animal = cycAccess.getKnownConstantByGuid(ANIMAL_GUID_STRING); CycConstant biologyVocabularyMt = cycAccess.getKnownConstantByGuid( BIOLOGY_VOCABULARY_MT_GUID_STRING); CycConstant performedBy = cycAccess.getKnownConstantByGuid(PERFORMED_BY_GUID_STRING); CycConstant doneBy = cycAccess.getKnownConstantByGuid(DONE_BY_GUID_STRING); CycConstant siblings = cycAccess.getKnownConstantByGuid(SIBLINGS_GUID_STRING); CycConstant generalLexiconMt = cycAccess.getKnownConstantByGuid( GENERAL_LEXICON_MT_GUID_STRING); CycConstant paraphraseMt = cycAccess.getKnownConstantByGuid(PARAPHRASE_MT_GUID_STRING); CycConstant mtTimeWithGranularityDimFn = cycAccess.getKnownConstantByGuid( MT_TIME_WITH_GRANULARITY_DIM_FN_GUID_STRING); CycConstant mtSpace = cycAccess.getKnownConstantByGuid(MT_SPACE_GUID_STRING); CycConstant now = cycAccess.getKnownConstantByGuid(NOW_GUID_STRING); CycConstant timePoint = cycAccess.getKnownConstantByGuid(TIMEPOINT_GUID_STRING); //(#$MtSpace (#$MtTimeWithGranularityDimFn #$Now #$TimePoint) #$WorldGeographyMt) ELMt worldGeographyMtNow = cycAccess.makeELMt( new CycNaut( mtSpace, new CycNaut(mtTimeWithGranularityDimFn, now, timePoint), worldGeographyMt)); // isa assertTrue(cycAccess.isa(brazil, country, worldGeographyMt)); assertTrue(cycAccess.isa(brazil, country, worldGeographyMtNow)); assertTrue(cycAccess.isa(brazil, country)); // isGenlOf assertTrue(cycAccess.isGenlOf(animal, dog, biologyVocabularyMt)); assertTrue(cycAccess.isGenlOf(animal, dog)); // isGenlPredOf assertTrue(cycAccess.isGenlPredOf(doneBy, performedBy, baseKB)); assertTrue(cycAccess.isGenlPredOf(doneBy, performedBy)); // isGenlInverseOf assertTrue(cycAccess.isGenlInverseOf(siblings, siblings, biologyVocabularyMt)); assertTrue(cycAccess.isGenlInverseOf(siblings, siblings)); // isGenlMtOf if (!cycAccess.isOpenCyc()) { assertTrue(cycAccess.isGenlMtOf(baseKB, biologyVocabularyMt)); } /* // tests proper receipt of narts from the server. String script = "(csetq all-narts nil)"; cycAccess.converseVoid(script); script = "(progn \n" + " (do-narts (nart) \n" + " (cpush nart all-narts)) \n" + " nil)"; cycAccess.converseVoid(script); script = "(clet (nart) \n" + " (csetq nart (first all-narts)) \n" + " (csetq all-narts (rest all-narts)) \n" + " nart)"; long numberGood = 0; long numberNil = 0; while (true) { Object obj = cycAccess.converseObject(script); if (obj.equals(nil)) break; assertTrue(obj instanceof CycNart); CycNart cycNart = (CycNart) obj; assertTrue(cycNart.cyclify() instanceof String); String script2 = "(find-nart " + cycNart.stringApiValue() + ")"; Object obj2 = cycAccess.converseObject(script2); if (cycNart.equals(obj)) numberGood++; else numberNil++; } assertTrue(numberGood > 20 * numberNil); script = "(csetq all-narts nil)"; cycAccess.converseVoid(script); */ } catch (Throwable e) { e.printStackTrace(); fail(e.toString()); } long endMilliseconds = System.currentTimeMillis(); System.out.println(" " + (endMilliseconds - startMilliseconds) + " milliseconds"); }
2
void actionDeleteCurrent() { Form form = (Form) tabPanel.getSelectedComponent(); boolean delete = MessageDialog.confirmQuestion("Odstranění serveru", "Potvrďte odstranění serveru " + form.getTitle() + ".", this); if (delete) { int serverId = tabPanel.getSelectedIndex(); servers.remove(serverId); tabPanel.remove(serverId); } }
1
public boolean nextMatch(int userID){ this.scoreList = this.runningMatch.getScoreList(); this.finishedMatches.add(this.runningMatch); if(upcomingMatches.peek() != null){ this.runningMatch = upcomingMatches.poll(); this.runningMatch.setLeftUser(alstLeftUser.toArray(new Integer[0])); this.runningMatch.setScoreList(this.scoreList); return true; } return false; }
1
public ArrayList<UndoableItem> redoFunction() { ArrayList<UndoableItem> toReturn = new ArrayList<>(); if (redoStack.isEmpty()) { return null; } else { ArrayList<UndoableItem> cur = (ArrayList<UndoableItem>) this.redoStack.pop(); this.undoStack.push(cur); for (UndoableItem ui : cur) { toReturn.add(ui); if (ui.getDitem() instanceof Panel) { // for (Layer l : ((Panel) cur.getDitem()).getLayers()) { for (PathItem pi : ((Panel) ui.getDitem()).getLines()) { if (!pi.isHidden()) { toReturn.add(new UndoableItem(pi, ui.getActionType())); } } } } return toReturn; } }
5
@Test public void test1() throws PersistitException { System.out.print("test1 "); final Exchange ex = _persistit.getExchange("persistit", "TransactionTest1", true); ex.removeAll(); final Transaction txn = ex.getTransaction(); txn.begin(); try { for (int i = 0; i < 10; i++) { ex.getValue().put("String value #" + i + " for test1"); ex.clear().append("test1").append(i).store(); } for (int i = 3; i < 10; i += 3) { ex.clear().append("test1").append(i).remove(Key.GTEQ); } txn.commit(); } finally { txn.end(); } for (int i = -1; i < 12; i++) { ex.clear().append("test1").append(i).fetch(); if ((i < 0) || (i >= 10) || ((i != 0) && ((i % 3) == 0))) { assertTrue(!ex.getValue().isDefined()); } else { assertTrue(ex.getValue().isDefined()); assertEquals(ex.getValue().get(), "String value #" + i + " for test1"); } } txn.begin(); try { ex.removeAll(); txn.commit(); } finally { txn.end(); } for (int i = -1; i < 12; i++) { ex.clear().append("test1").append(i).fetch(); assertTrue(!ex.getValue().isDefined()); } txn.begin(); try { ex.removeTree(); txn.commit(); } finally { txn.end(); } assertTrue(!ex.getTree().isValid()); try { ex.clear().append("test1").hasChildren(); fail("Should have thrown an exception"); } catch (Exception e) { // ok } System.out.println("- done"); }
9
@Override public boolean urunSil(int urunID) { /* HbmIslemler hbm = new HbmIslemler(); * */ try { /* return hbm.sil(urunID, Urun.class); * */ Urun urun = urunBul(urunID); if(urun != null){ if(urunler.remove(urun)) return true; } return false; } catch (HibernateException ex) { ex.printStackTrace(); throw ex; } }
3
public static boolean analysisVMXM(AnalysisOutput o, List<AnalysisOutput> candidates) throws MorphException { int idxXVerb = VerbUtil.endsWithXVerb(o.getStem()); if(idxXVerb==-1) return false; o.setXverb(o.getStem().substring(idxXVerb)); String eogan = o.getStem().substring(0,idxXVerb); String[] stomis = null; if(eogan.endsWith("아")||eogan.endsWith("어")) { stomis = EomiUtil.splitEomi(eogan.substring(0,eogan.length()-1),eogan.substring(eogan.length()-1)); if(stomis[0]==null) return false; }else { stomis = EomiUtil.splitEomi(eogan, ""); if(stomis[0]==null||!(stomis[1].startsWith("아")||stomis[1].startsWith("어"))) return false; } String[] irrs = IrregularUtil.restoreIrregularVerb(stomis[0], stomis[1]); if(irrs!=null) { o.setStem(irrs[0]); o.addElist(irrs[1]); } else { o.setStem(stomis[0]); o.addElist(stomis[1]); } if(DictionaryUtil.getVerb(o.getStem())!=null) { o.setPos(PatternConstants.POS_VERB); o.setPatn(PatternConstants.PTN_VMXM); o.setScore(AnalysisOutput.SCORE_CORRECT); candidates.add(o); } return (o.getScore()==AnalysisOutput.SCORE_CORRECT); }
9
@Override public List<TransMode> load(Criteria criteria, GenericLoadQuery loadGeneric, Connection conn) throws DaoQueryException { int pageSize = 10; List paramList = new ArrayList<>(); StringBuilder sb = new StringBuilder(WHERE); String queryStr = new QueryMapper() { @Override public String mapQuery() { Appender.append(DAO_ID_TRANSMODE, DB_TRANSMODE_ID_MODE, criteria, paramList, sb, AND); Appender.append(DAO_TRANSMODE_NAME, DB_TRANSMODE_NAME, criteria, paramList, sb, AND); if (paramList.isEmpty()) { return LOAD_QUERY; } else { return sb.insert(0, LOAD_QUERY).toString(); } } }.mapQuery(); try { return loadGeneric.sendQuery(queryStr, paramList.toArray(), pageSize, conn, (ResultSet rs, int rowNum) -> { TransMode bean = new TransMode(); bean.setIdMode(rs.getInt(DB_TRANSMODE_ID_MODE)); bean.setNameMode(rs.getString(DB_TRANSMODE_NAME)); return bean; }); } catch (DaoException ex) { throw new DaoQueryException(ERR_TRANSMODE_LOAD, ex); } }
2
public static void printFormulaInfo() { System.out.println("*********************************\nVariable Information"); //print out the variables for(int i = 1; i < variables.size(); i++) { Variable v = variables.get(i); System.out.println(v.getName() + "\tAssignment:" + (v.getAssignment()==Variable.UNASSIGNED?"Unassign":(v.getAssignment()==Variable.TRUE?"True ":"False ")) + "\tTimes pos: " + v.getTimesPositive() + "\tTimes neg: " + v.getTimesNegative() + "\tUnit clauses: '" + v.getUnitClauses().toString() + "'"); } //print out the clauses System.out.println("\nLiterals in Clauses: < # > means variable '#' has been assigned"); for(int i = 0; i < clauses.size(); i++) { Clause c = clauses.get(i); System.out.println("Clause " + i + " is " + (c.isSatisfied()?"Satisfied":"Unsatisfied(yet)")); for(Literal l : c.getLiterals()) { if(l.getVariable().getAssignment() == Variable.UNASSIGNED) System.out.print(l + " "); else System.out.print("<" + l + "> "); } System.out.println(""); } System.out.println(""); }
7
public static int[] find(int[] arr, int windowSize, boolean print) { if(arr==null || arr.length==0) { return new int[]{}; } int[] result = new int[arr.length]; int idx = 0; MyQueueWithMaxMin<Integer> queue = new MyQueueWithMaxMin<Integer>(arr.length); int i=0; queue.offer(arr[i++]); if(i<arr.length) queue.offer(arr[i++]); if(i<arr.length) queue.offer(arr[i++]); result[idx++] = queue.max(); for(; i<arr.length; i++) { queue.offer(arr[i]); queue.poll(); result[idx++] = queue.max(); } result = Arrays.copyOfRange(result, 0, idx); if(print) System.out.println(Arrays.toString(result)); return result; }
6
private static String verifyUrlPagination(String url,ArrayList<String> exclusionKeyWords) { if (!url.toLowerCase().startsWith("http")) { return null; } try { new URL(url); } catch (MalformedURLException e) { Logger.getLogger(Crawler.class).debug("Exception :"+e.getMessage() + " Description :"+ e.toString()); return null; } for(int i=0; i<exclusionKeyWords.size(); i++) { if(url.contains(exclusionKeyWords.get(i))){ return null; } } return url; }
4
public void run(){ int data; while(true){ data = buffer.consume(); } }
1
protected String getNestedUsage(String[] args, int level, Method method, T player) throws CommandException { StringBuilder command = new StringBuilder(); command.append("/"); for (int i = 0; i <= level; ++i) { command.append(args[i] + " "); } Map<String, Method> map = commands.get(method); boolean found = false; command.append("<"); Set<String> allowedCommands = new HashSet<String>(); for (Map.Entry<String, Method> entry : map.entrySet()) { Method childMethod = entry.getValue(); found = true; if (hasPermission(childMethod, player)) { Command childCmd = childMethod.getAnnotation(Command.class); allowedCommands.add(childCmd.aliases()[0]); } } if (allowedCommands.size() > 0) { command.append(StringUtil.joinString(allowedCommands, "|", 0)); } else { if (!found) { command.append("?"); } else { //command.append("action"); throw new CommandPermissionsException(); } } command.append(">"); return command.toString(); }
5
public Tela() { initComponents(); //JFileChooser configure txt jFileChooser1.setAcceptAllFileFilterUsed(false); FileFilter filter = new FileNameExtensionFilter("TXT File","txt"); jFileChooser1.setFileFilter(filter); jFileChooser1.setControlButtonsAreShown(false); jFileChooser1.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { File selectedFile = jFileChooser1.getSelectedFile(); if(JFileChooser.OPEN_DIALOG == jFileChooser1.getDialogType()) { String path = selectedFile.getParent() + "/"; OrganizadorPalavras organizador = new OrganizadorPalavras(); ManipuladorArquivo manipula = new ManipuladorArquivo(path, selectedFile.getName()); String arquivoDeTexto = manipula.leArquivo(organizador); System.out.println(arquivoDeTexto); if(Desktop.isDesktopSupported()) { File htmlFile = new File(System.getProperty("user.dir") + "/Textos/" +"html.html"); try { Desktop.getDesktop().open(htmlFile); } catch (IOException ex) { Logger.getLogger(Tela.class.getName()).log(Level.SEVERE, null, ex); } } } } }); }
3
public int[][] generateMatrix(int n) { int[][] matrix = new int[n][n]; int[] layerTotal = new int[n/2 + 1]; layerTotal[0] = 0; // layer length outside current index for (int i = 0; i < n; i++) { int v = Math.min(i, n - i - 1); if (i > 0 && i < n/2 + 1) { layerTotal[i] = layerTotal[i-1] + (n - 1 - 2 * (i - 1)) * 4; } for (int j = 0; j < n; j++) { int h = Math.min(j, n - j - 1); int layer = Math.min(v, h); int layerLen = (n - 1 - 2 * layer); if (v <= h) { // top or bottom if (i < n / 2) { // top matrix[i][j] = layerTotal[layer] + j - layer + 1; } else { // bottom matrix[i][j] = layerTotal[layer] + layerLen * 2 + (n - 1 - layer) - j + 1; } } else { // left or right if (j < n / 2) { // left matrix[i][j] = layerTotal[layer] + layerLen * 3 + (n - 1 - layer) - i + 1; } else { // right matrix[i][j] = layerTotal[layer] + layerLen + i - layer + 1; } } } } return matrix; }
7
public Number multiplyNumbers(Number a, Number b) throws NumberClassNotFoundException { Number product = null; if (a instanceof Double && b instanceof Double) { product = new Double(roundDouble(a.doubleValue() * b.doubleValue())); } else if (a instanceof Integer && b instanceof Integer) { product = new Integer(a.intValue() * b.intValue()); } else if (a instanceof Float && b instanceof Float) { product = new Float(roundFloat(a.floatValue() * b.floatValue())); } else if (a instanceof Long && b instanceof Long) { product = new Long(a.longValue() * b.longValue()); } else { throw new NumberClassNotFoundException(a.getClass() + " and " + b.getClass() + " not currently supported."); } return product; }
8
private void processCNumber(AnalyzeContext context){ if(nStart == -1 && nEnd == -1){//初始状态 if(CharacterUtil.CHAR_CHINESE == context.getCurrentCharType() && ChnNumberChars.contains(context.getCurrentChar())){ //记录数词的起始、结束位置 nStart = context.getCursor(); nEnd = context.getCursor(); } }else{//正在处理状态 if(CharacterUtil.CHAR_CHINESE == context.getCurrentCharType() && ChnNumberChars.contains(context.getCurrentChar())){ //记录数词的结束位置 nEnd = context.getCursor(); }else{ //输出数词 this.outputNumLexeme(context); //重置头尾指针 nStart = -1; nEnd = -1; } } //缓冲区已经用完,还有尚未输出的数词 if(context.isBufferConsumed()){ if(nStart != -1 && nEnd != -1){ //输出数词 outputNumLexeme(context); //重置头尾指针 nStart = -1; nEnd = -1; } } }
9
public static String longestTwoUniqueSubStr(String str){ List<String> chars = new ArrayList<String>(); String maxSubString = ""; String current = ""; int i=0; for(char c: str.toCharArray()){ chars.clear(); chars.add(c + ""); current = c + ""; for(int j = i+1; j <str.length(); j++){ if(chars.contains(str.charAt(j) + "")){ current = current + str.charAt(j); if(current.length() > maxSubString.length()){ maxSubString = current; } } else if(chars.size() == 1){ chars.add(str.charAt(j) + ""); current = current + str.charAt(j); if(current.length() > maxSubString.length()){ maxSubString = current; } }else{ if(current.length() > maxSubString.length()){ maxSubString = current; } current = ""; break; } } i++; } return maxSubString; }
7
public static void cobrirLinhas(Coluna naoincluir, Solucao solucao){ for(Coluna col : solucao.getColunas()){ if(col.getNome()!= naoincluir.getNome()){ ArrayList<Integer> valores_cobertos_pela_coluna = col.getCobertura(); for(Integer linha : valores_cobertos_pela_coluna){ if(!(solucao.getLinhasCobertas().contains(linha))){ solucao.getLinhasCobertas().add(linha); } } } } }
4
public HTTPResponse handle(HTTPRequest req) { { Iterator<Plugin> it = plugins.iterator(); while ( it.hasNext() ) { Plugin thisPlugin = it.next(); if ( thisPlugin.handles(req) ) return thisPlugin.handle(req); } } String debugData = req.getMethod()+" "+req.getPath()+"<br>"; debugData += "Host: "+req.getHost()+"<br>"; debugData += "<h3>Client Headers</h3>"; Iterator<String> it = req.headers.keySet().iterator(); while ( it.hasNext() ) { String d = it.next(); debugData += d+": "+req.headers.get(d)+"<br>"; } return ErrorFactory.internalServerError("No plugins where able to handle your request.<br>"+debugData); }
3
public void updatePos() { if(--time >= 0) { for (int i = 0; i < Map.getHeight(); i++) { for (int j = 0; j < Map.getWidth(); j++) { if (Utils.distance(j, i, px, py) == radius - time) Map.addAttack(new Attack(j, i, father)); } } } }
4
@SuppressWarnings("rawtypes") public List loadList(final List<Long> ids) { if (ids == null || ids.isEmpty()) return new ArrayList(0); // 因为要保持有序,所以按照id顺序创建对象 List<POJO> prjs = new ArrayList<POJO>(ids.size()) { private static final long serialVersionUID = 1L; { for (int i = 0; i < ids.size(); i++) add(null); } }; List<Long> noCacheIds = new ArrayList<Long>(); for (int i = 0; i < ids.size(); i++) { long id = ids.get(i); POJO obj = (POJO) getCache(id); if (obj != null) prjs.set(i, obj); else { noCacheIds.add(id); } } if (noCacheIds.size() > 0) { List<? extends POJO> objs = batchGet(noCacheIds); if (objs != null) for (POJO obj : objs) { prjs.set(ids.indexOf(obj.getId()), obj); } } return prjs; }
9
public void addClientEvent(int event){ for (Team team : playmode.getTeams()) { for (User user : team.getUser()) { ArrayList<Integer> events = userIDtoClientEvents.get(user.getID()); events.add(event); userIDtoClientEvents.put(user.getID(), events); } } }
2
public Object invoke(Object proxy, Method m, Object[] args) throws Throwable { Object result; try { System.out.println("before method " + m.getName()); result = m.invoke(obj, args); result = interceptor.around(result); } catch (InvocationTargetException e) { throw e.getTargetException(); } catch (Exception e) { throw new RuntimeException("unexpected invocation exception: " + e.getMessage()); } finally { System.out.println("after method " + m.getName()); } return result; }
2