text
stringlengths
14
410k
label
int32
0
9
public int getMessageId() { if (messageId == -1) { messageId = nextId(); } return messageId; }
1
public static void main(String[]args){ int[] numbers = new int [5]; Scanner scanner = new Scanner(System.in); /*for (int i=0; i<5; i++) { System.out.println("Write numbers[" + i + " ] = "); numbers[i] = scanner.nextInt(); System.out.println(verifyIfNumberIsPrime(numbers[i])); } */ int[][] matrix = new int[4][4]; for (int i=0; i<4; i++) for (int j=0; j<4; j++) { System.out.println("Write matrix [ " + i + "]["+ j + "] = "); matrix[i][j]=scanner.nextInt(); } for (int i=0; i<4; i++) for (int j=0; j<4; j++) { if (j==0) System.out.println(matrix[i][j]); else System.out.print(matrix[i][j]); } for (int i=0; i<4; i++) for (int j=0; j<4; j++) { if (j>i) if (j==1) System.out.println(matrix[i][j]); else System.out.print(matrix[i][j]); } scanner.close(); }
9
public String[] getInterfaces() { if (cachedInterfaces != null) return cachedInterfaces; String[] rtn = null; if (interfaces == null) rtn = new String[0]; else { int n = interfaces.length; String[] list = new String[n]; for (int i = 0; i < n; ++i) list[i] = constPool.getClassInfo(interfaces[i]); rtn = list; } cachedInterfaces = rtn; return rtn; }
3
public static ServiceTime getServiceTime(Address srcAddr, Address dstAddr) { ServiceTime serviceTime = new ServiceTime(); serviceTime.setSrcAddr(srcAddr); serviceTime.setDstAddr(dstAddr); String url = "http://www.sf-express.com/dwr/call/plaincall/ServiceTimeManager.getServiceTime_omp.dwr"; List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(Params.CALLCOUNT, "1")); params.add(new BasicNameValuePair(Params.PAGE, "/cn/sc/delivery_step/enquiry/serviceTime.html")); params.add(new BasicNameValuePair(Params.HTTPSESSIONID, "AA221E633D34390E22017CDF44103228")); params.add(new BasicNameValuePair(Params.SCRIPTSESSIONID, "ABCFB15977C207121D3B56939B23DAE5952")); params.add(new BasicNameValuePair(Params.C0SCRIPTNAME, "ServiceTimeManager")); params.add(new BasicNameValuePair(Params.C0METHODNAME, "getServiceTime_omp")); params.add(new BasicNameValuePair(Params.C0ID, "0")); params.add(new BasicNameValuePair(Params.C0PARAM0, "string:" + srcAddr.getProvince())); params.add(new BasicNameValuePair(Params.C0PARAM1, "string:" + srcAddr.getCity())); params.add(new BasicNameValuePair(Params.C0PARAM2, "string:" + srcAddr.getArea())); params.add(new BasicNameValuePair(Params.C0PARAM3, "string:" + srcAddr.getCountry())); params.add(new BasicNameValuePair(Params.C0PARAM4, "string:" + dstAddr.getProvince())); params.add(new BasicNameValuePair(Params.C0PARAM5, "string:" + dstAddr.getCity())); params.add(new BasicNameValuePair(Params.C0PARAM6, "string:" + dstAddr.getArea())); params.add(new BasicNameValuePair(Params.C0PARAM7, "string:" + dstAddr.getCountry())); params.add(new BasicNameValuePair(Params.C0PARAM8, "string:" + SendTime.day)); params.add(new BasicNameValuePair(Params.C0PARAM9, "string:" + SendTime.hour)); params.add(new BasicNameValuePair(Params.C0PARAM10, "string:" + SendTime.minute)); params.add(new BasicNameValuePair(Params.C0PARAM11, "string:CN")); params.add(new BasicNameValuePair(Params.C0PARAM12, "string:SC")); params.add(new BasicNameValuePair(Params.BATCHID, "24")); HttpClientUtils.doPost(url, params); String rtn = HttpClientUtils.getResponseAsString(); // System.out.println(rtn); // map<快递编号, 时间差(day)> Map<String, Double> serviceTmMap = new HashMap<String, Double>(); List<String> blearDeliverTmList = StringParserUtils.parseString(rtn, "(?:s\\d{1,}.blearDeliverTm=\")(.*?)(?:\";)"); List<String> productTypeList = StringParserUtils.parseString(rtn, "(?:s\\d{1,}.productTypeCode=\")(.*?)(?:\";)"); log.info(srcAddr.toString() + " >> " + dstAddr.toString()); for (int i = 0; i < blearDeliverTmList.size(); ++i) { serviceTmMap.put(productTypeList.get(i), calHours(blearDeliverTmList.get(i) + ":00")); // serviceTmList.add(new ServiceTime(srcAddr, dstAddr, // blearDeliverTmList.get(i), productTypeList.get(i))); // log.info(productTypeList.get(i) + " - " + // blearDeliverTmList.get(i)); } Set<String> keys = serviceTmMap.keySet(); for (Iterator it = keys.iterator(); it.hasNext();) { String key = (String) it.next(); // System.out.println(key); // System.out.println(serviceTmMap.get(key)); if ("T1".equals(key)) { serviceTime.setT1_time(serviceTmMap.get("T1")); } if ("T4".equals(key)) { serviceTime.setT4_time(serviceTmMap.get("T4")); } if ("SP4".equals(key)) { serviceTime.setSp4_time(serviceTmMap.get("SP4")); } if ("SP5".equals(key)) { serviceTime.setSp5_time(serviceTmMap.get("SP5")); } if ("T6".equals(key)) { serviceTime.setT6_time(serviceTmMap.get("T6")); } if ("T801".equals(key)) { serviceTime.setT801_time(serviceTmMap.get("T801")); } } // 加时信息 AddTimeInfo addTimeInfo = AddTimeAddrUtils.getAddTimeAddr(dstAddr); serviceTime.setAddTimeInfo(addTimeInfo); return serviceTime; }
8
public void changeController(EU2Country country) { String sid = go.getString("id"); boolean b = false; EU2Country prevController = null; for (int i = 0; i < scenario.numCountries() && !b; i++) { GenericList provs = scenario.getCountry(i).go.getList("controlledprovinces"); for (String controlled : provs) { if (controlled.equals(sid)) { b = true; prevController = scenario.getCountry(i); break; } } // for (int j = 0; j < provs.size() && !b; j++) { // if (provs.getVariable(j).equals(sid)) { // provs.removeVariable(j); // b = true; // } // } } if (b) { prevController.removeControlledProv(Integer.parseInt(sid)); country.addControlledProv(Integer.parseInt(sid)); } // country.go.getList("controlledprovinces").add(sid, false); }
5
@SuppressWarnings("unchecked") @Override public E get(int index) { if (index < 0 || index >= size) { throw new IndexOutOfBoundsException("Index " + index + "for size " + size + " is out of bounds"); } return (E) data[index]; }
2
void initKey(Integer[] kcs) { for (int i = 0; i < kcs.length; i++) { try { keyMapping.put(kcs[i], Board.class.getMethod(methodName[i])); } catch (NoSuchMethodException | SecurityException e) { e.printStackTrace(); } } }
2
public void load() { try { // First do checks to create the initial file if(!file.exists()) { if(file.getParentFile()!=null) file.getParentFile().mkdirs(); if(file.createNewFile()) super.save(file); else throw new Exception("Cannot load: File can not be created!"); } // Then do checks to save the file super.load(file); } catch (Exception e) { e.printStackTrace(); } }
4
private void checkTreeMembership(Position<T> pos) { if (!(pos instanceof GeneralTreeNode) || !((GeneralTreeNode<T>) pos).sameTree(this)) { throw new IllegalArgumentException("Invalid position for this " + "tree."); } }
2
public void selectNextgenaration() { List<MaxOneChromosome> nextGen = new ArrayList<MaxOneChromosome>(); // Copy over a portion of the population unchanged, based on // the elitism ratio. int idx = Math.round(this.size() * elitism); for (int i = 0; i < idx; i++) { nextGen.add(this.get(i)); } while (idx < populationsize) { if (rand.nextFloat() <= crossover) { List<MaxOneChromosome> parents = bestSelector.selectParent(this, rand.nextInt(Math.round(populationsize * (crossover)))); for (MaxOneChromosome parnet : parents) { List<MaxOneChromosome> childrens = parnet.doCrossover(parents.get(rand.nextInt(parents.size()))); for (MaxOneChromosome child : childrens) { if (rand.nextFloat() <= mutation) { nextGen.add(child.doMutate()); } else { nextGen.add(child); } idx++; } // Repeat for the second child, if there is room. } } else { // No crossover, so copy verbatium. if (rand.nextFloat() <= mutation) { nextGen.add(this.get(idx)); } else { nextGen.add(this.get(idx)); } idx++; } } this.removeAll(this); this.addAll(nextGen); }
7
public void setStats(boolean forceNewStats, Stats stats) { switch(stats.getMode()) { case 0: setStatsOsuStandard(forceNewStats, stats); return; case 1: setStatsTaiko(forceNewStats, stats); return; case 2: setStatsCTB(forceNewStats, stats); return; case 3: setStatsOsuMania(forceNewStats, stats); return; } throw new IllegalArgumentException("Mode must be between 0 and 3!"); }
4
public void run() { byte[] ack_buffer = new byte[ACK_SIZE]; do { try { ack_buffer = new byte[ACK_SIZE]; DatagramPacket receivePacket = new DatagramPacket( ack_buffer, ack_buffer.length); clientSocket.receive(receivePacket); } catch (Exception e) { } int ack_num = Utilities.getPacketNum(ack_buffer); if (checkForPacket(ack_buffer) == false) { addPacket(ack_buffer); } } while (!end); }
3
protected synchronized void flushAndClose( int code, String message, boolean remote ) { if ( flushandclosestate ) { return; } closecode = code; closemessage = message; closedremotely = remote; flushandclosestate = true; wsl.onWriteDemand( this ); // ensures that all outgoing frames are flushed before closing the connection try { wsl.onWebsocketClosing( this, code, message, remote ); } catch ( RuntimeException e ) { wsl.onWebsocketError( this, e ); } if ( draft != null ) draft.reset(); handshakerequest = null; }
3
public boolean setOption( String op, String val ) { if( op.equals( "crossesAt" ) ) // specifies where axis crosses (double value { catCross = Short.valueOf( val ); } else if( op.equals( "orientation" ) ) { // axis orientation minMax or maxMin -- fReverse fReverse = (val.equals( "maxMin" )); // means in reverse order ByteTools.updateGrBit( grbit, fReverse, 2 ); } else if( op.equals( "crosses" ) ) { // specifies how axis crosses it's perpendicular axis (val= max, min, autoZero) -- fbetween + fMaxCross?/fAutoCross + fMaxCross if( val.equals( "max" ) ) { // TODO: this is probly wrong fMaxCross = true; ByteTools.updateGrBit( grbit, fMaxCross, 7 ); } else if( val.equals( "mid" ) ) { fBetween = false; ByteTools.updateGrBit( grbit, fBetween, 0 ); } else if( val.equals( "autoZero" ) ) { fBetween = true; // is this correct?? ByteTools.updateGrBit( grbit, fBetween, 0 ); } else if( val.equals( "min" ) ) { ; } // TODO: ??? } else if( op.equals( "tickMarkSkip" ) ) //val= how many tick marks to skip before next one is drawn -- catMark -- catsterrange only? { catMark = Integer.valueOf( val ).shortValue(); } else if( op.equals( "tickLblSkip" ) ) { catLabel = Integer.valueOf( val ).shortValue(); } else { return false; // not handled } updateRecord(); return true; }
9
int insertKeyRehash(short val, int index, int hash, byte state) { // compute the double hash final int length = _set.length; int probe = 1 + (hash % (length - 2)); final int loopIndex = index; int firstRemoved = -1; /** * Look until FREE slot or we start to loop */ do { // Identify first removed slot if (state == REMOVED && firstRemoved == -1) firstRemoved = index; index -= probe; if (index < 0) { index += length; } state = _states[index]; // A FREE slot stops the search if (state == FREE) { if (firstRemoved != -1) { insertKeyAt(firstRemoved, val); return firstRemoved; } else { consumeFreeSlot = true; insertKeyAt(index, val); return index; } } if (state == FULL && _set[index] == val) { return -index - 1; } // Detect loop } while (index != loopIndex); // We inspected all reachable slots and did not find a FREE one // If we found a REMOVED slot we return the first one found if (firstRemoved != -1) { insertKeyAt(firstRemoved, val); return firstRemoved; } // Can a resizing strategy be found that resizes the set? throw new IllegalStateException("No free or removed slots available. Key set full?!!"); }
9
public static boolean almostEquals(double v1, double v2) { if (v1 == v2) { return true; } if (Double.isNaN(v1) || Double.isNaN(v2) || Double.isInfinite(v1) || Double.isInfinite(v2)) { return false; } long bits1 = Double.doubleToLongBits(v1); long bits2 = Double.doubleToLongBits(v2); if (bits1 < 0) { bits1 = Long.MIN_VALUE - bits1; } if (bits2 < 0) { bits2 = Long.MIN_VALUE - bits2; } long diff = bits1 - bits2; if (diff < 0) { diff = -diff; } return diff < maxUlps; }
8
public MainView(Piece[][] board){ this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setBounds(0, 0, 1150, 870); boardPane = new JLayeredPane(); boardPane.setBounds(100, 100,800,800); getContentPane().add(boardPane); this.addMainMenuBar(); chessBoard = new JPanel(); chessBoard.setLayout( new GridLayout(8, 8) ); chessBoard.setBounds(0, 0, 800,800); boardPane.add(chessBoard, JLayeredPane.DEFAULT_LAYER); for(int i=7; i>=0; i--){ for(int j=0; j<=7; j++){ Square square = new Square(j,i); if((j % 2==0 && i % 2 != 0) || (j% 2!=0 && i%2 ==0)){ square.setBackground(Color.GRAY); square.setBackColor(Color.GRAY); }else{ square.setBackground(Color.WHITE); square.setBackColor(Color.WHITE); } chessPiece = new ChessPiece(board[i][j].getType(), board[i][j].getColor()); square.add(chessPiece); chessBoard.add( square ); } } /* int pawnCount = 0; Square pawnSquare = new Square(); outBoard = new JPanel(); outBoard.setLayout(new GridLayout(16,2)); outBoard.setBounds(810, 10, 300, 790); boardPane.add(outBoard, JLayeredPane.DEFAULT_LAYER); for(int i=7; i>=0; i--){ for(int j=0; j<=7; j++){ Square square = new Square(j,i); if(board[i][j].getType()!=null){ if(board[i][j].getType()=="Pawn"){ if(pawnCount==0){ chessPiece = new ChessPiece(board[i][j].getType(), board[i][j].getColor()); square.add(chessPiece); pawnSquare = square; pawnCount++; }else{ pawnCount++; } } //chessPiece = new ChessPiece(board[i][j].getType(), board[i][j].getColor()); //square.add(chessPiece); //outBoard.add( square ); } } } pawnSquare.add(new JLabel(""+pawnCount+"")); outBoard.add( pawnSquare ); */ this.setVisible(true); }
6
private JComponent drawDialogPane() { // Create the panel JPanel panel = new JPanel(); panel.setLayout(new GridLayout()); panel.setBorder(BorderFactory.createTitledBorder("Product")); //Getting items from warehouse tab StockItem[] items = new StockItem[model.getWarehouseTableModel().getRowCount()]; model.getWarehouseTableModel().getTableRows().toArray(items); // Initialize the textfields productSelectionJComboBoxField = new JComboBox<StockItem>(items); productSelectionJComboBoxField.setSize(this.getPreferredSize().width, this.getPreferredSize().height); barCodeField = new JTextField(); quantityField = new JTextField("1"); setNameField(new JTextField()); priceField = new JTextField(); // Fill the dialog fields if the bar code text field loses focus productSelectionJComboBoxField.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if(e.getStateChange() == ItemEvent.SELECTED){ fillDialogFields((StockItem)e.getItem()); } } }); barCodeField.setEditable(false); getNameField().setEditable(false); priceField.setEditable(false); // == Add components to the panel panel.add(productSelectionJComboBoxField, getItemConstraints(0,0,2)); // - bar code panel.add(new JLabel("Bar code:"), getItemConstraints(0,1,1)); panel.add(barCodeField, getItemConstraints(1,1,1)); // - amount panel.add(new JLabel("Amount:"), getItemConstraints(0,2,1)); panel.add(quantityField, getItemConstraints(1,2,1)); // - name panel.add(new JLabel("Name:"), getItemConstraints(0,3,1)); panel.add(getNameField(), getItemConstraints(1,3,1)); // - price panel.add(new JLabel("Price:"), getItemConstraints(0,4,1)); panel.add(priceField, getItemConstraints(1,4,1)); // Create and add the button addItemButton = new JButton("Add to cart"); addItemButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { addItemEventHandler(); } }); panel.add(addItemButton, getItemConstraints(0,5,2)); return panel; }
1
private boolean insertBlock(Block gameBlock) { if (!gameBlock.insert(gameGrid)) { --lives; if (lives != 0) { gameGrid.wipe(); return gameBlock.insert(gameGrid); } return false; } return true; }
2
public static void startupClassify() { { 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)) { _StartupClassify.helpStartupClassify1(); } if (Stella.currentStartupTimePhaseP(4)) { Logic.$FINDSUPERSANDSUBSDESCRIPTION$.setDefaultValue(null); Logic.$CLASSIFICATIONSESSION$.setDefaultValue(null); Logic.$CLASSIFY_FROM_NON_INFERABLE_PARENTS_ONLYp$.setDefaultValue(new Boolean(true)); } if (Stella.currentStartupTimePhaseP(5)) { { Stella_Class renamed_Class = Stella.defineClassFromStringifiedSource("MARKER-TABLE", "(DEFCLASS MARKER-TABLE (STANDARD-OBJECT) :DOCUMENTATION \"Used to record (mark) a set of objects.\nCan be optimized for testing only, or also for recall.\" :SLOTS ((TEST-TABLE :TYPE HASH-TABLE) (RECALL-TABLE :TYPE LIST) (SUPPORTS-RECALL? :TYPE BOOLEAN)))"); renamed_Class.classConstructorCode = Native.find_java_method("edu.isi.powerloom.logic.MarkerTable", "newMarkerTable", new java.lang.Class [] {}); renamed_Class.classSlotAccessorCode = Native.find_java_method("edu.isi.powerloom.logic.MarkerTable", "accessMarkerTableSlotValue", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.MarkerTable"), Native.find_java_class("edu.isi.stella.Symbol"), Native.find_java_class("edu.isi.stella.Stella_Object"), java.lang.Boolean.TYPE}); } { Stella_Class renamed_Class = Stella.defineClassFromStringifiedSource("CLASSIFICATION-CACHE", "(DEFCLASS CLASSIFICATION-CACHE (STANDARD-OBJECT) :DOCUMENTATION \"Records various kinds of data about a description\nduring a classification session.\" :SLOTS ((INFERABLE-DIRECT-SUBDESCRIPTIONS :TYPE (LIST OF DESCRIPTION)) (CACHE-UPCLASSIFICATION-TIMESTAMP :TYPE INTEGER :INITIALLY -1) (CACHE-DOWNCLASSIFICATION-TIMESTAMP :TYPE INTEGER :INITIALLY -1) (INTRODUCTION-TIMESTAMP :TYPE INTEGER :INITIALLY 0)))"); renamed_Class.classConstructorCode = Native.find_java_method("edu.isi.powerloom.logic.ClassificationCache", "newClassificationCache", new java.lang.Class [] {}); renamed_Class.classSlotAccessorCode = Native.find_java_method("edu.isi.powerloom.logic.ClassificationCache", "accessClassificationCacheSlotValue", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.ClassificationCache"), Native.find_java_class("edu.isi.stella.Symbol"), Native.find_java_class("edu.isi.stella.Stella_Object"), java.lang.Boolean.TYPE}); } { Stella_Class renamed_Class = Stella.defineClassFromStringifiedSource("CLASSIFICATION-SESSION", "(DEFCLASS CLASSIFICATION-SESSION (STANDARD-OBJECT) :SLOTS ((CLASSIFICATION-WORLD :TYPE WORLD) (CLASSIFICATION-CACHE-TABLE :TYPE (HASH-TABLE OF OBJECT CLASSIFICATION-CACHE) :ALLOCATION :EMBEDDED) (CLASSIFICATION-TIMECLOCK :TYPE INTEGER :INITIALLY 0) (INTRODUCTION-TIMESTAMP-STACK :TYPE (LIST OF INTEGER-WRAPPER) :INITIALLY (LIST 0)) (EVERYTHING-CLASSIFIED? :TYPE BOOLEAN) (LAST-CACHE-TABLE-KEY :TYPE LOGIC-OBJECT) (LAST-CACHE-TABLE-VALUE :TYPE CLASSIFICATION-CACHE)))"); renamed_Class.classConstructorCode = Native.find_java_method("edu.isi.powerloom.logic.ClassificationSession", "newClassificationSession", new java.lang.Class [] {}); renamed_Class.classSlotAccessorCode = Native.find_java_method("edu.isi.powerloom.logic.ClassificationSession", "accessClassificationSessionSlotValue", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.ClassificationSession"), 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)) { _StartupClassify.helpStartupClassify2(); Stella.defineFunctionObject("LIST-UNCLASSIFIED-RELATIONS", "(DEFUN (LIST-UNCLASSIFIED-RELATIONS (CONS OF NAMED-DESCRIPTION)) (|&REST| (OPTIONS OBJECT)) :DOCUMENTATION \"Collect all named description in the module defined by the :module option (which defaults\nto the current module) that were not (or will not be) classified due to their lack of\nnon-inferable/primitive ancestor relations. If :module was explicitly specified as NULL,\nlook in all currently defined modules. If `:local?' is specified as TRUE only look\nin the specified module but not any modules it inherits. For backwards compatibility,\nthis command also supports the old <module> <local?> arguments specified without keywords.\" :PUBLIC? TRUE :COMMAND? TRUE :EVALUATE-ARGUMENTS? FALSE)", Native.find_java_method("edu.isi.powerloom.logic.Logic", "listUnclassifiedRelations", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Cons")}), Native.find_java_method("edu.isi.powerloom.logic.Logic", "listUnclassifiedRelationsEvaluatorWrapper", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Cons")})); Stella.defineFunctionObject("UPCLASSIFY-INSTANCES", "(DEFUN UPCLASSIFY-INSTANCES ((MODULE MODULE) (LOCAL? BOOLEAN)) :DOCUMENTATION \"Classify instances local to 'module' and inherited\nby 'module'. If 'local?', don't classify inherited descriptions. If\n'module' is NULL, classify descriptions in all modules.\")", Native.find_java_method("edu.isi.powerloom.logic.Logic", "upclassifyInstances", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Module"), java.lang.Boolean.TYPE}), null); Stella.defineFunctionObject("CLASSIFY-INSTANCES", "(DEFUN CLASSIFY-INSTANCES (|&REST| (OPTIONS OBJECT)) :DOCUMENTATION \"Classify instances visible in the module defined by the :module option (which\ndefaults to the current module). If :module was explicitly specified as NULL,\nclassify instances in all modules. If `:local?' is specified as TRUE only classify\ninstances that belong to the specified module but not any modules it inherits. For\nbackwards compatibility, this command also supports the old <module> <local?>\narguments specified without keywords.\n\nConceptually, the classifier operates by comparing each instance with all\nconcepts in the hierarchy, searching for a proof for each pairing indicating\nthat the instance belongs to the concept. Whenever a new `is-a' relation is\ndiscovered, the classifier adds an `is-a' link between the instance and the\nconcept, thereby recording an additional fact about the instance. The\nimplemented classification algorithm is relatively efficient -- it works hard at\nlimiting the number of concepts or relations that need to be checked for\npossible is-a relationships.\n\" :PUBLIC? TRUE :COMMAND? TRUE :EVALUATE-ARGUMENTS? FALSE)", Native.find_java_method("edu.isi.powerloom.logic.Logic", "classifyInstances", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Cons")}), Native.find_java_method("edu.isi.powerloom.logic.Logic", "classifyInstancesEvaluatorWrapper", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Cons")})); Stella.defineFunctionObject("LIST-UNCLASSIFIED-INSTANCES", "(DEFUN (LIST-UNCLASSIFIED-INSTANCES (CONS OF LOGIC-OBJECT)) (|&REST| (OPTIONS OBJECT)) :DOCUMENTATION \"Collect all instances in the module defined by the :module option (which defaults\nto the current module) that were not (or will not be) classified due to their lack of\nnon-inferable/primitive type assertions. If :module was explicitly specified as NULL,\nlook in all currently defined modules. If `:local?' is specified as TRUE only look\nin the specified module but not any modules it inherits. For backwards compatibility,\nthis command also supports the old <module> <local?> arguments specified without keywords.\" :PUBLIC? TRUE :COMMAND? TRUE :EVALUATE-ARGUMENTS? FALSE)", Native.find_java_method("edu.isi.powerloom.logic.Logic", "listUnclassifiedInstances", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Cons")}), Native.find_java_method("edu.isi.powerloom.logic.Logic", "listUnclassifiedInstancesEvaluatorWrapper", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Cons")})); Stella.defineFunctionObject("UPCLASSIFY-ALL-DESCRIPTIONS", "(DEFUN UPCLASSIFY-ALL-DESCRIPTIONS () :DOCUMENTATION \"Classify all named descriptions.\")", Native.find_java_method("edu.isi.powerloom.logic.Logic", "upclassifyAllDescriptions", new java.lang.Class [] {}), null); Stella.defineFunctionObject("UPCLASSIFY-ALL-INSTANCES", "(DEFUN UPCLASSIFY-ALL-INSTANCES () :DOCUMENTATION \"Classify all named instances.\")", Native.find_java_method("edu.isi.powerloom.logic.Logic", "upclassifyAllInstances", new java.lang.Class [] {}), null); Stella.defineFunctionObject("ALL-EQUIVALENT-COLLECTIONS", "(DEFUN (ALL-EQUIVALENT-COLLECTIONS (CONS OF LOGIC-OBJECT)) ((SELF LOGIC-OBJECT) (REFLEXIVE? BOOLEAN)) :PUBLIC? TRUE)", Native.find_java_method("edu.isi.powerloom.logic.LogicObject", "allEquivalentCollections", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.LogicObject"), java.lang.Boolean.TYPE}), null); Stella.defineFunctionObject("ALL-CYCLES", "(DEFUN (ALL-CYCLES (CONS OF CONS)) ((MODULE MODULE) (LOCAL? BOOLEAN)) :PUBLIC? TRUE :DOCUMENTATION \"Return a list of lists of descriptions that are\nprovably co-extensional.\")", Native.find_java_method("edu.isi.powerloom.logic.Logic", "allCycles", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Module"), java.lang.Boolean.TYPE}), null); Stella.defineFunctionObject("STARTUP-CLASSIFY", "(DEFUN STARTUP-CLASSIFY () :PUBLIC? TRUE)", Native.find_java_method("edu.isi.powerloom.logic._StartupClassify", "startupClassify", new java.lang.Class [] {}), null); { MethodSlot function = Symbol.lookupFunction(Logic.SYM_LOGIC_STARTUP_CLASSIFY); KeyValueList.setDynamicSlotValue(function.dynamicSlots, Logic.SYM_STELLA_METHOD_STARTUP_CLASSNAME, StringWrapper.wrapString("_StartupClassify"), Stella.NULL_STRING_WRAPPER); } } 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 *SPECIALMARKERTABLE* MARKER-TABLE :DOCUMENTATION \"Special variable that points to the marker table \nreferenced by the function 'test-special-marker-table?'.\")"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *FINDSUPERSANDSUBSDESCRIPTION* DESCRIPTION NULL :DOCUMENTATION \"Points to a possibly unnamed description being\ntemporarily classified.\")"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *CLASSIFICATIONSESSION* CLASSIFICATION-SESSION NULL :PUBLIC? TRUE :DOCUMENTATION \"Points to state of on-going classification session.\")"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *CACHE-INFERABLE-SUBCOLLECTIONS?* BOOLEAN TRUE :DOCUMENTATION \"If TRUE, prevents caching of computations of\nall inferable subcollections of a collection.\")"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *CLASSIFY-FROM-NON-INFERABLE-PARENTS-ONLY?* BOOLEAN TRUE :DOCUMENTATION \"If true (the default) only consider those relations (or instances) for\nclassification that have at least one non-inferable parent (or type). This\ncan greatly reduce the classification effort. To find entities that were\nleft unclassified due to this optimization use `list-unclassified-relations'\nor `list-unclassified-instances'.\" :PUBLIC? TRUE)"); } } finally { Stella.$CONTEXT$.set(old$Context$000); Stella.$MODULE$.set(old$Module$000); } } }
7
public void createNewarea(int x, int y, String areaName) { int i, j = 0; Room r = null; Vector<Room> newRoomList = new Vector<Room>(); for (i = 0; i < x; i++) { for (j = 0; j < y; j++) { System.out.print("make room" + String.valueOf(i) + '-' + String.valueOf(j)); r = new Room(); r.init(); r.setRoomFilename("image/" + areaName + String.valueOf(i) + '-' + String.valueOf(j)); r.setDescription(areaName + String.valueOf(i) + '-' + String.valueOf(j)); if (i < (x - 1)) { r.setNorthExit("image/" + areaName + String.valueOf(i + 1) + '-' + String.valueOf(j)); System.out.print("; north:" + String.valueOf(i + 1) + '-' + String.valueOf(j)); } if (i > 0) { r.setSouthExit("image/" + areaName + String.valueOf(i - 1) + '-' + String.valueOf(j)); System.out.print("; south:" + String.valueOf(i - 1) + '-' + String.valueOf(j)); } if (j > 0) { r.setWestExit("image/" + areaName + String.valueOf(i) + '-' + String.valueOf(j - 1)); System.out.print("; west:" + String.valueOf(i) + '-' + String.valueOf(j - 1)); } if (j < (y - 1)) { r.setEastExit("image/" + areaName + String.valueOf(i) + '-' + String.valueOf(j + 1)); System.out.print("; east:" + String.valueOf(i) + '-' + String.valueOf(j + 1)); } if (j == 0 && i == 0) { r.setSouthExit(this.getRoomFilename()); this.setNorthExit(r.getRoomFilename()); } System.out.println(""); newRoomList.add(r); World.getArea().getRooms().add(r); } } Enumeration<Room> e = newRoomList.elements(); while (e.hasMoreElements()) { Room rm = (Room) e.nextElement(); rm.initializeExits(); } this.initializeExits(); }
9
public NoeudItineraire rechercheNoeudLivraisonPrecedent(Livraison livraison){ int idxPremierePlageNonVide = 0; for(int idxPlage=0; idxPlage< this.plagesHoraire.size(); idxPlage++){ List<Livraison> listeLivraison = this.plagesHoraire.get(idxPlage).getAllLivraison(); if(listeLivraison.size() == 0){ idxPremierePlageNonVide++; } else{ int idxLiv = listeLivraison.indexOf(livraison); if(idxLiv != -1){ //Livraison trouv�e if(idxLiv == 0){ //premiere livraison de la plage horaire: on regarde la plage horaire precedente if(idxPlage == idxPremierePlageNonVide){ //premiere plage horaire: on retourne l'entrepot return this.entrepot; } else{ return this.plagesHoraire.get(idxPlage-1).getDerniereLivraison(); } } else{ return this.plagesHoraire.get(idxPlage).getLivraison(idxLiv-1); } } } } return null; }
5
private void eltran(double[][] a, double[][] zz, int[] ordr, int n) { int i, j, m; for (i = 0; i < n; i++) { for (j = i + 1; j < n; j++) { zz[i][j] = 0.0; zz[j][i] = 0.0; } zz[i][i] = 1.0; } if (n <= 2) { return; } for (m = n - 1; m >= 2; m--) { for (i = m; i < n; i++) { zz[i][m - 1] = a[i][m - 2]; } i = ordr[m - 1]; if (i != m) { for (j = m - 1; j < n; j++) { zz[m - 1][j] = zz[i - 1][j]; zz[i - 1][j] = 0.0; } zz[i - 1][m - 1] = 1.0; } } }
7
@Override public void deserialize(Buffer buf) { rank = buf.readShort(); if (rank < 0 || rank > 2300) throw new RuntimeException("Forbidden value on rank = " + rank + ", it doesn't respect the following condition : rank < 0 || rank > 2300"); bestDailyRank = buf.readShort(); if (bestDailyRank < 0 || bestDailyRank > 2300) throw new RuntimeException("Forbidden value on bestDailyRank = " + bestDailyRank + ", it doesn't respect the following condition : bestDailyRank < 0 || bestDailyRank > 2300"); bestRank = buf.readShort(); if (bestRank < 0 || bestRank > 2300) throw new RuntimeException("Forbidden value on bestRank = " + bestRank + ", it doesn't respect the following condition : bestRank < 0 || bestRank > 2300"); victoryCount = buf.readShort(); if (victoryCount < 0) throw new RuntimeException("Forbidden value on victoryCount = " + victoryCount + ", it doesn't respect the following condition : victoryCount < 0"); arenaFightcount = buf.readShort(); if (arenaFightcount < 0) throw new RuntimeException("Forbidden value on arenaFightcount = " + arenaFightcount + ", it doesn't respect the following condition : arenaFightcount < 0"); }
8
public void start() { if (this.cPointer == 0) { throw new ClosedException(); } final int r = ppaml_phase_start(this.cPointer); switch (r) { case 0: break; case 1: throw new ClockAcquisitionException(); case 2: throw new OTFWriterEntryException(); default: throw new UnexpectedReturnValueError(r); } }
4
@Override public void update(Observable obs, Object obj) { if (obs == robotInstance.getJoystickHandler()) { // We've hit a joystick error - disable everything if (connected) { robotInstance.getPacketTransmitter().terminate(); jEnableBtn.setEnabled(false); jEnableBtn.setText("Enable"); jConnectBtn.setText("Connect"); jRoboStatus.setText("Disconnected"); enabled = false; connected = false; } System.exit(0); } else if (obs == robotInstance.getDashboardData()) { // New Packet! ArrayList<String> bundles = robotInstance.getDashboardData().getBundles(); String[] dashboardData = new String[bundles.size()]; for (int i = 0; i < bundles.size(); i++) dashboardData[i] = bundles.get(i); dsList.setListData(dashboardData); } }
4
public GameWindow getGameWindow() { boolean test = false; if (test || m_test) { System.out.println("Controls :: getGameWindow() BEGIN"); } if (test || m_test) { System.out.println("Controls :: getGameWindow() END"); } return m_gameWindow; }
4
@Override /** * This method will be used by the table component to get * value of a given cell at [row, column] */ public Object getValueAt(int rowIndex, int columnIndex) { Object value = null; Problem problem = problems.get(rowIndex); switch (columnIndex) { case COLUMN_TITLE: value = problem.getProblemName(); break; case COLUMN_FILE_NAME: value = problem.getFilename(); break; case COLUMN_INPUT: value = problem.getInput(); break; case COLUMN_OUTPUT: value = problem.getOutput(); break; } return value; }
4
@Override public int takeStep() { fillVariables(); if (gloBallBehindLine(this.gloBall, -0.3, ourField)) { if (upper) { goToGloDestination(this.gloMyPosition, this.gloUpperDefensePosition, 0.1); System.out.println("UPPER: " + this.gloUpperDefensePosition); } else { goToGloDestination(this.gloMyPosition, this.gloDownerDefensePosition, 0.1); System.out.println("DOWNER: " + this.gloDownerDefensePosition); } } else if (gloBallBehindLine(this.gloBall, -0.1, ourField)){ myRobotAPI.setBehindBall(this.egoRandomGoal); } else { myRobotAPI.setSteerHeading(this.egoRandomGoal.t); myRobotAPI.setSpeed(1); if (myRobotAPI.canKick()) { myRobotAPI.kick(); } } if (myRobotAPI.blocked()) { MessageEvent message = new MessageEvent(); message.setReceiver(0); message.setType(Type.trainer); message.setEventText("Delantero bloqueado"); myRobotAPI.getTeamManager().sendMessage(message); } return RobotAPI.ROBOT_OK; }
5
public boolean equals(Object obj) { if(!(obj instanceof Pair)) { return false; } if(obj == this) { return true; } if(obj.equals(null)) { return false; } @SuppressWarnings("unchecked") Pair<T, U> p = (Pair<T, U>)obj; if(p.getFirst() == null || p.getSecond() == null) { System.out.println("Pair NULL Error!"); return false; } if(p.getFirst().equals(t) && p.getSecond().equals(u)) { return true; } else { return false; } }
7
public void addAll(Collection<Feature> features) { this.features.addAll(features); }
0
public Integer getInteger(String expression, Object context) throws XPathExpressionException { assert(expression != null); if(context == null) { assert(document != null); context = document; } return ((Double) xpath.evaluate(expression, context, XPathConstants.NUMBER)).intValue(); }
1
private static int buildRows(OutlineModel model) { model.addRow(new OutlineTestRow("First")); //$NON-NLS-1$ model.addRow(new OutlineTestRow("Second, but with a really long piece of non-pre-wrapped text.")); //$NON-NLS-1$ model.addRow(new OutlineTestRow("Third, but with a\nreally long piece\nof pre-wrapped text.")); //$NON-NLS-1$ model.addRow(new OutlineTestRow("Bob")); //$NON-NLS-1$ int rowCount = 4; Row row = new OutlineTestRow("Marley"); //$NON-NLS-1$ row.setCanHaveChildren(true); for (int i = 0; i < 10; i++) { row.addChild(new OutlineTestRow(Integer.toString(i))); rowCount++; if (i == 5) { Row sub = new OutlineTestRow("Submarine"); //$NON-NLS-1$ row.setCanHaveChildren(true); sub.addChild(new OutlineTestRow("Yellow")); //$NON-NLS-1$ sub.addChild(new OutlineTestRow("Black")); //$NON-NLS-1$ sub.addChild(new OutlineTestRow("Blue")); //$NON-NLS-1$ row.addChild(sub); rowCount += 4; } if (i == 9) { Row sub = new OutlineTestRow("Last"); //$NON-NLS-1$ row.setCanHaveChildren(true); sub.addChild(new OutlineTestRow("Me")); //$NON-NLS-1$ sub.addChild(new OutlineTestRow("You")); //$NON-NLS-1$ sub.addChild(new OutlineTestRow("Them")); //$NON-NLS-1$ row.addChild(sub); rowCount += 4; } } model.addRow(row); rowCount++; return rowCount; }
3
public static double fTestValueGivenFprob(double fProb, int df1, int df2) { // Create an array F-test value array int fTestsNum = 100; // length of array double[] fTestValues = new double[fTestsNum]; fTestValues[0] = 0.0001D; // lowest array value fTestValues[fTestsNum - 1] = 10000.0D; // highest array value // calculate array increment - log scale double diff = (Fmath.log10(fTestValues[fTestsNum - 1]) - Fmath.log10(fTestValues[0])) / (fTestsNum - 1); // Fill array for (int i = 1; i < fTestsNum - 1; i++) { fTestValues[i] = Math.pow(10.0D, (Fmath.log10(fTestValues[i - 1]) + diff)); } // calculate F test probability array corresponding to F-test value array double[] fTestProb = new double[fTestsNum]; for (int i = 0; i < fTestsNum; i++) { fTestProb[i] = Stat.fTestProb(fTestValues[i], df1, df2); } // calculate F-test value for provided probability // using bisection procedure double fTest0 = 0.0D; double fTest1 = 0.0D; double fTest2 = 0.0D; // find bracket for the F-test probabilities and calculate F-Test value from above arrays boolean test0 = true; boolean test1 = true; int i = 0; int endTest = 0; while (test0) { if (fProb == fTestProb[i]) { fTest0 = fTestValues[i]; test0 = false; test1 = false; } else { if (fProb > fTestProb[i]) { test0 = false; if (i > 0) { fTest1 = fTestValues[i - 1]; fTest2 = fTestValues[i]; endTest = -1; } else { fTest1 = fTestValues[i] / 10.0D; fTest2 = fTestValues[i]; } } else { i++; if (i > fTestsNum - 1) { test0 = false; fTest1 = fTestValues[i - 1]; fTest2 = 10.0D * fTestValues[i - 1]; endTest = 1; } } } } // call bisection method if (test1) fTest0 = fTestBisect(fProb, fTest1, fTest2, df1, df2, endTest); return fTest0; }
8
public boolean equals(Object obj) { if (obj == this) return true; if (obj == null) return false; if (obj.getClass() != this.getClass()) return false; Picture that = (Picture) obj; if (this.width() != that.width()) return false; if (this.height() != that.height()) return false; for (int x = 0; x < width(); x++) for (int y = 0; y < height(); y++) if (!this.get(x, y).equals(that.get(x, y))) return false; return true; }
8
public void InsertaInicio (int idProceso, String nombreProceso, boolean recibido) { if (VaciaLista()) PrimerNodo = UltimoNodo = new NodosListaProceso(nombreProceso); else PrimerNodo = new NodosListaProceso(nombreProceso,PrimerNodo ); }
1
private void render() { System.out.println("Render"); GridSquare[][] grid = gl.getGrid(); for(int col = 0; col < grid.length; col++) { for(int row = 0; row < grid[col].length; row++) { if (grid[row][col].player == EPlayer.None) System.out.print("-"); else if (grid[row][col].player == EPlayer.P1) System.out.print("o"); else System.out.print("x"); if(grid[row][col].turnNumber >= 0) System.out.print(grid[row][col].turnNumber.toString()); System.out.print("("); for(Integer it : grid[row][col].undefinedTurns.keySet()) { if (grid[row][col].undefinedTurns.get(it) == EPlayer.None) System.out.print("-"); else if (grid[row][col].undefinedTurns.get(it) == EPlayer.P1) System.out.print("o"); else System.out.print("x"); if(it >= 0) System.out.print(it.toString()); } System.out.print(")"); } System.out.println(""); } }
9
public void writeDataFile(String contentToWrite, String personName, String topic) { // Checks if personName is null of empty if (personName == null || personName.isEmpty()) { personName = "All Speakers"; } // Checks if topic is null or empty if (topic == null || topic.isEmpty()) { topic = "All Topics"; } String fileName = personName + "_" + topic; if (fileName.endsWith(" ")){ fileName = fileName.substring(0, fileName.length()-1); } // Create folder to store folers for each search File dir1 = new File(System.getProperty("user.home") + "/Desktop","Provincial Mining"); dir1.mkdir(); // Create folder to store .PRO, .html, .txt, and .docx files // for each search File dir2 = new File(dir1, "Quebec"); dir2.mkdir(); // Creates a folder in previously created directoy named the person's // name followed by the topic File dir3 = new File(dir2, fileName); dir3.mkdir(); // Replace generic tags with <ignore> tags needed for .PRO and .txt files contentToWrite = contentToWrite.replace("<name>", "<ignore>"); contentToWrite = contentToWrite.replace("</name>", "</ignore>"); contentToWrite = contentToWrite.replace("<topic>", "<ignore>"); contentToWrite = contentToWrite.replace("</topic>", "</ignore>"); contentToWrite = contentToWrite.replace("<date>", "<ignore>"); contentToWrite = contentToWrite.replace("</date>", "</ignore>"); // Write .PRO file writeToFile(dir3, fileName + ".PRO", contentToWrite); // Write .txt file writeToFile(dir3, fileName + ".txt", contentToWrite); // Replaces <ignore> tags with <p> html tags contentToWrite = contentToWrite.replace("<ignore>", "<p>"); contentToWrite = contentToWrite.replace("</ignore>", "</p>"); // Write .html file writeToFile(dir3, fileName + ".html", contentToWrite); // Open folder containing files just written try { Desktop.getDesktop().open(dir3); } catch (IOException ex) { Logger.getLogger(WriteFile.class.getName()).log(Level.SEVERE, null, ex); } }
6
@Override public boolean create(Particulier x) { String req = "INSERT INTO particulier ( email, motdepasse, nom, prenom, titre, adresse)\n" +"select \""+x.getEmail()+"\", \""+x.getMotDePasse()+"\", \""+x.getNom()+"\", \""+x.getPrenom()+"\", \""+x.getTitre()+"\", \""+x.getAdresse()+"\" from dual\n" +"where not exists (select * from particulier where email = \""+x.getEmail()+"\")" +"and not exists (select * from hotelier where email = \""+x.getEmail()+"\")"; Statement stm = null; try { stm = cnx.createStatement(); int n= stm.executeUpdate(req,Statement.RETURN_GENERATED_KEYS); if (n>0) { x.setParticulierId(n); stm.close(); return true; } } catch (SQLException exp) { } finally { if (stm!=null) try { stm.close(); } catch (SQLException e) { e.printStackTrace(); } } return false; }
4
@Override public void run() { try { InputStream in = socket.getInputStream();// read from the socket BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String html; while (!"".equals((html = reader.readLine()))) { System.out.println(html); } OutputStream out = socket.getOutputStream(); String response = "<h2>This is the " + counter + " request</h2>"; out.write("HTTP/1.1 200 OK\n".getBytes()); out.write("Content-Type: text/html; charset=utf-8\n".getBytes()); out.write((("Content-Length: " + response.length() + "\n\n").getBytes())); out.write(response.getBytes()); out.flush(); out.close(); } catch (IOException ex) { ex.getStackTrace(); } }
2
boolean clauseChainSpec(int tok) { if (tok == Token.colon) { tokenNext(); tok = tokPeek(); if (isSpecTerminator(tok)) return generateResidueSpecCode(new Token(Token.spec_chain, '\0', "spec_chain")); } if (tok == Token.asterisk) { tokenNext(); return true; } Token tokenChain; char chain; switch (tok) { // case Token.colon: // case Token.percent: // case Token.nada: // case Token.dot: I think this was incorrect. :.C?? // chain = '\0'; // break; case Token.integer: tokenChain = tokenNext(); if (tokenChain.intValue < 0 || tokenChain.intValue > 9) return invalidChainSpecification(); chain = (char) ('0' + tokenChain.intValue); break; case Token.identifier: tokenChain = tokenNext(); String strChain = (String) tokenChain.value; if (strChain.length() != 1) return invalidChainSpecification(); chain = strChain.charAt(0); if (chain == '?') return true; break; default: return invalidChainSpecification(); } return generateResidueSpecCode(new Token(Token.spec_chain, chain, "spec_chain")); }
9
private Node getOpposite(Node n){ int cur = n.getIndex(); int par = n.getParent().getIndex(); try{ if(cur == par + dim && cur / dim < dim - 1) return nodeMap[cur+dim]; if(cur == par - dim && cur / dim > 0) return nodeMap[cur-dim]; if(cur == par + 1 && cur % dim < dim - 1) return nodeMap[cur+1]; if(cur == par - 1 && cur % dim > 0) return nodeMap[cur-1]; }catch(Exception e){} return null; }
9
public static long convert32bitsLittleEndianToUnsignedInt(byte[] d) { return ((0xff & d[3])<<24) + ((0xff & d[2])<<16) + ((0xff & d[1])<<8) + (0xff & d[0]); }
0
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AlgebraicParticle other = (AlgebraicParticle) obj; if (exponent != other.exponent) return false; if (sign != other.sign) return false; return true; }
5
public static boolean isPrinterAvailable2(String printerName) { DocFlavor myFormat = DocFlavor.SERVICE_FORMATTED.PRINTABLE; PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet(); PrintService[] printers = PrintServiceLookup.lookupPrintServices(myFormat, aset); for (PrintService printService : printers) { if (printService.getName().equals(printerName)) { System.out.println(printService.getAttribute(PrinterIsAcceptingJobs.class)); System.out.println(printService.getAttribute(PrinterLocation.class)); System.out.println(printService.getAttribute(PrinterMakeAndModel.class)); System.out.println(printService.getAttribute(PrinterMessageFromOperator.class)); System.out.println(printService.getAttribute(PrinterMoreInfo.class)); System.out.println(printService.getAttribute(PrinterMoreInfoManufacturer.class)); System.out.println(printService.getAttribute(PrinterState.class)); System.out.println(printService.getAttribute(PrinterStateReasons.class)); System.out.println(printService.getAttribute(PrinterURI.class)); } } return false; }
2
@AfterClass public static void tearDownClass() { }
0
private String getTTenNum(){ if ((this.LinkIDNum++) >= 10000000) this.LinkIDNum=0; String returnnum ="0000000000"+ String.valueOf(this.LinkIDNum); return returnnum.substring(returnnum.length()-10); }
1
@Override public void update(double deltaTime) { desiredPosition = position.plus(controls.desiredMove()); rechargeTimeRemaining -= deltaTime; if (controls.shouldFire()){ if (rechargeTimeRemaining <= 0){ Vector2f spawnLocation = position.plus(size.x()/2, 0); world.spawnEntity(spawner, spawnLocation); rechargeTimeRemaining = rechargeTime; } } }
2
public static int traversal(TreeNode node, int prefix) { if (null != node) { if (null == node.left && null == node.right) { return prefix * 10 + node.val; } else if (null == node.left) { return traversal(node.right, prefix * 10 + node.val); } else if (null == node.right) { return traversal(node.left, prefix * 10 + node.val); } else { return traversal(node.left, prefix * 10 + node.val) + traversal(node.right, prefix * 10 + node.val); } } return prefix; }
5
private Opcode toOpcode(byte opcode) { switch (opcode) { case 0: return Opcode.CONTINIOUS; case 1: return Opcode.TEXT; case 2: return Opcode.BINARY; // 3-7 are not yet defined case 8: return Opcode.CLOSING; case 9: return Opcode.PING; case 10: return Opcode.PONG; // 11-15 are not yet defined default: return null; } }
6
public ArrayList<UndoableItem> undoFunction() { ArrayList<UndoableItem> toReturn = new ArrayList<>(); if (undoStack.isEmpty()) { return null; } else { ArrayList<UndoableItem> cur = (ArrayList<UndoableItem>) this.undoStack.pop(); this.redoStack.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
public ServiceContainer() { }
0
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Action other = (Action) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; }
6
public int findPeakElement(int[] num){ int fore = -9999999, next=-9999999; for(int i = 0; i < num.length; i++){ if(i+1 == num.length) next = -999999; else next = num[i+1]; if(num[i] >= fore && num[i] >= next) return i; } return 0; }
4
@Override public Point2D next() { Point2D ret = new Point2D.Double(x, y); double e2 = 2*error; if (e2 > -dy) { error -= dy; x += sx; } if (e2 < dx) { error += dx; y += sy; } return ret; }
2
public static void startupHttpClient() { { Object old$Module$000 = Stella.$MODULE$.get(); Object old$Context$000 = Stella.$CONTEXT$.get(); try { Native.setSpecial(Stella.$MODULE$, Stella.getStellaModule("/HTTP", Stella.$STARTUP_TIME_PHASE$ > 1)); Native.setSpecial(Stella.$CONTEXT$, ((Module)(Stella.$MODULE$.get()))); if (Stella.currentStartupTimePhaseP(2)) { Http.KWD_MAC = ((Keyword)(GeneralizedSymbol.internRigidSymbolWrtModule("MAC", null, 2))); Http.SYM_HTTP_HTTP_HEADERS = ((Symbol)(GeneralizedSymbol.internRigidSymbolWrtModule("HTTP-HEADERS", null, 0))); Http.SGT_STELLA_FILE_INPUT_STREAM = ((Surrogate)(GeneralizedSymbol.internRigidSymbolWrtModule("FILE-INPUT-STREAM", Stella.getStellaModule("/STELLA", true), 1))); Http.SGT_STELLA_INPUT_STREAM = ((Surrogate)(GeneralizedSymbol.internRigidSymbolWrtModule("INPUT-STREAM", Stella.getStellaModule("/STELLA", true), 1))); Http.KWD_POST = ((Keyword)(GeneralizedSymbol.internRigidSymbolWrtModule("POST", null, 2))); Http.KWD_GET = ((Keyword)(GeneralizedSymbol.internRigidSymbolWrtModule("GET", null, 2))); Http.SYM_STELLA_LET = ((Symbol)(GeneralizedSymbol.internRigidSymbolWrtModule("LET", Stella.getStellaModule("/STELLA", true), 0))); Http.SYM_STELLA_INPUT_STREAM = ((Symbol)(GeneralizedSymbol.internRigidSymbolWrtModule("INPUT-STREAM", Stella.getStellaModule("/STELLA", true), 0))); Http.SYM_STELLA_NULL = ((Symbol)(GeneralizedSymbol.internRigidSymbolWrtModule("NULL", Stella.getStellaModule("/STELLA", true), 0))); Http.SYM_STELLA_UNWIND_PROTECT = ((Symbol)(GeneralizedSymbol.internRigidSymbolWrtModule("UNWIND-PROTECT", Stella.getStellaModule("/STELLA", true), 0))); Http.SYM_STELLA_PROGN = ((Symbol)(GeneralizedSymbol.internRigidSymbolWrtModule("PROGN", Stella.getStellaModule("/STELLA", true), 0))); Http.SYM_STELLA_SETQ = ((Symbol)(GeneralizedSymbol.internRigidSymbolWrtModule("SETQ", Stella.getStellaModule("/STELLA", true), 0))); Http.SYM_HTTP_OPEN_URL_STREAM = ((Symbol)(GeneralizedSymbol.internRigidSymbolWrtModule("OPEN-URL-STREAM", null, 0))); Http.SYM_STELLA_WHEN = ((Symbol)(GeneralizedSymbol.internRigidSymbolWrtModule("WHEN", Stella.getStellaModule("/STELLA", true), 0))); Http.SYM_STELLA_DEFINEDp = ((Symbol)(GeneralizedSymbol.internRigidSymbolWrtModule("DEFINED?", Stella.getStellaModule("/STELLA", true), 0))); Http.SYM_STELLA_CLOSE_STREAM = ((Symbol)(GeneralizedSymbol.internRigidSymbolWrtModule("CLOSE-STREAM", Stella.getStellaModule("/STELLA", true), 0))); Http.KWD_METHOD = ((Keyword)(GeneralizedSymbol.internRigidSymbolWrtModule("METHOD", null, 2))); Http.KWD_HEADERS = ((Keyword)(GeneralizedSymbol.internRigidSymbolWrtModule("HEADERS", null, 2))); Http.KWD_CONTENT = ((Keyword)(GeneralizedSymbol.internRigidSymbolWrtModule("CONTENT", null, 2))); Http.SGT_HTTP_HTTP_HEADERS = ((Surrogate)(GeneralizedSymbol.internRigidSymbolWrtModule("HTTP-HEADERS", null, 1))); Http.SYM_HTTP_STARTUP_HTTP_CLIENT = ((Symbol)(GeneralizedSymbol.internRigidSymbolWrtModule("STARTUP-HTTP-CLIENT", null, 0))); Http.SYM_STELLA_METHOD_STARTUP_CLASSNAME = ((Symbol)(GeneralizedSymbol.internRigidSymbolWrtModule("METHOD-STARTUP-CLASSNAME", Stella.getStellaModule("/STELLA", true), 0))); } if (Stella.currentStartupTimePhaseP(5)) { Stella.defineStellaTypeFromStringifiedSource("(DEFTYPE HTTP-HEADERS (KEY-VALUE-LIST OF STRING-WRAPPER STRING-WRAPPER))"); { Stella_Class renamed_Class = Stella.defineClassFromStringifiedSource("HTTP-EXCEPTION", "(DEFCLASS HTTP-EXCEPTION (READ-EXCEPTION) :PUBLIC-SLOTS ((ERROR-CODE :TYPE INTEGER)))"); renamed_Class.classConstructorCode = Native.find_java_method("edu.isi.webtools.http.HttpException", "newHttpException", new java.lang.Class [] {Native.find_java_class("java.lang.String")}); } } if (Stella.currentStartupTimePhaseP(6)) { Stella.finalizeClasses(); } if (Stella.currentStartupTimePhaseP(7)) { Stella.defineFunctionObject("DECOMPOSE-INTERNET-URL", "(DEFUN (DECOMPOSE-INTERNET-URL STRING STRING STRING STRING STRING STRING STRING) ((URL STRING)) :DOCUMENTATION \"Takes an internet style URL and returns the components of\nthat URL as specified below. Missing elements return the empty string \\\"\\\".\n PROTOCOL USERNAME:PASSWORD DOMAIN PORT PATH QUERY FRAGMENT\n\n o Protocol. The access protocol.\n\n Those schemes which refer to internet protocols mostly have a\n common syntax for the rest of the object name. This starts with a\n double slash '//' to indicate its presence, and continues until\n the following slash '/':\n\n o An optional user name, if required (as it is with a few FTP servers).\n The password, if present, follows the user name, separated from it by a colon;\n the user name and optional password are followed by a commercial at sign '@'. \n o The internet domain name of the host\n o The port number, if it is not the default number for the protocol,\n is given in decimal notation after a colon.\n o Path The path is a hierarchical representation of a particular path. It may \n define details of how the client should communicate with the server, including\n information to be passed transparently to the server without any processing by\n the client.\n The path is interpreted in a manner dependent on the scheme being used.\n Generally, the reserved slash '/' character (ASCII 2F hex) denotes a level in a\n hierarchical structure, the higher level part to the left of the slash.\n o Query is the part of the hierarchical information following a '?' character.\n o Fragment is the part of the hierarchical information following a '#' character.\n\nReferences: http://www.gbiv.com/protocols/uri/rfc/rfc3986.html\" :PUBLIC? TRUE)", Native.find_java_method("edu.isi.webtools.http.Http", "decomposeInternetUrl", new java.lang.Class [] {Native.find_java_class("java.lang.String"), Native.find_java_class("[Ljava.lang.Object;")}), null); Stella.defineFunctionObject("COMPOSE-INTERNET-URL", "(DEFUN (COMPOSE-INTERNET-URL STRING) ((PROTOCOL STRING) (USERINFO STRING) (HOST STRING) (PORT INTEGER) (PATH STRING) (QUERY STRING) (FRAGMENT STRING)) :DOCUMENTATION \"The inverse to `decompose-internet-url'. Builds a URL string from the supplied\ncomponents. Undefined portions can be supplied as NULL or the empty string.\" :PUBLIC? TRUE)", Native.find_java_method("edu.isi.webtools.http.Http", "composeInternetUrl", new java.lang.Class [] {Native.find_java_class("java.lang.String"), Native.find_java_class("java.lang.String"), Native.find_java_class("java.lang.String"), java.lang.Integer.TYPE, Native.find_java_class("java.lang.String"), Native.find_java_class("java.lang.String"), Native.find_java_class("java.lang.String")}), null); Stella.defineFunctionObject("URL-PATH-TO-FILENAME", "(DEFUN (URL-PATH-TO-FILENAME STRING) ((PATH STRING)) :DOCUMENTATION \"Transform a URL `path' into a valid native filename for the local OS.\" :PUBLIC? TRUE)", Native.find_java_method("edu.isi.webtools.http.Http", "urlPathToFilename", new java.lang.Class [] {Native.find_java_class("java.lang.String")}), null); Stella.defineFunctionObject("HANDLE-HTTP-HEADER-FIRST-LINE", "(DEFUN (HANDLE-HTTP-HEADER-FIRST-LINE STRING INTEGER STRING) ((LINE STRING) (FIELDS HTTP-HEADERS)) :DOCUMENTATION \"Handles the first line of an http header. \nReturns version, response code, response message. The first\nline is inserted into `fields' fields with the empty string key \\\"\\\"\nThis is a low-level utility routine that can be used to build custom\nmessage parsing code.\" :PUBLIC? TRUE)", Native.find_java_method("edu.isi.webtools.http.Http", "handleHttpHeaderFirstLine", new java.lang.Class [] {Native.find_java_class("java.lang.String"), Native.find_java_class("edu.isi.stella.KeyValueList"), Native.find_java_class("[Ljava.lang.Object;")}), null); Stella.defineFunctionObject("HANDLE-HTTP-HEADER-OTHER-LINE", "(DEFUN HANDLE-HTTP-HEADER-OTHER-LINE ((LINE STRING) (FIELDS HTTP-HEADERS)) :DOCUMENTATION \"Handles header lines other than the first one.\nEach such line is inserted into `fields' as keyword value pairs.\nThis is a low-level utility routine that can be used to build custom\nmessage parsing code.\" :PUBLIC? TRUE)", Native.find_java_method("edu.isi.webtools.http.Http", "handleHttpHeaderOtherLine", new java.lang.Class [] {Native.find_java_class("java.lang.String"), Native.find_java_class("edu.isi.stella.KeyValueList")}), null); Stella.defineFunctionObject("READ-HTTP-HEADER-LINE", "(DEFUN (READ-HTTP-HEADER-LINE STRING) ((STREAM INPUT-STREAM)))", Native.find_java_method("edu.isi.webtools.http.Http", "readHttpHeaderLine", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.InputStream")}), null); Stella.defineFunctionObject("READ-HTTP-HEADER", "(DEFUN (READ-HTTP-HEADER INTEGER STRING STRING) ((STREAM INPUT-STREAM) (FIELDS HTTP-HEADERS)) :DOCUMENTATION \"Reads the HTTP header from `stream', parses the header fields\nand stores the results in `fields'. The first line of the response will be\nstored in `fields' with the empty string \\\"\\\" as the key. Other values will\nhave the header name as the key. The first return value is the response code\nof the HTTP request. A response of 200 indicates success. Other common\nresponses are 404 (page not found). The second return value is the message\nassociated with the code. The third return value is the version information.\nIf the stream ends before a valid header is read, then `null' is returned for\nall values.\" :PUBLIC? TRUE)", Native.find_java_method("edu.isi.webtools.http.Http", "readHttpHeader", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.InputStream"), Native.find_java_class("edu.isi.stella.KeyValueList"), Native.find_java_class("[Ljava.lang.Object;")}), null); Stella.defineFunctionObject("GET-CONTENT-AND-LENGTH", "(DEFUN (GET-CONTENT-AND-LENGTH OBJECT LONG-INTEGER) ((CONTENT OBJECT)))", Native.find_java_method("edu.isi.webtools.http.Http", "getContentAndLength", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Stella_Object"), Native.find_java_class("[Ljava.lang.Object;")}), null); Stella.defineFunctionObject("WRITE-HTTP-REQUEST", "(DEFUN WRITE-HTTP-REQUEST ((STREAM OUTPUT-STREAM) (METHOD KEYWORD) (HOST STRING) (URL-PATH STRING) (HEADERS HTTP-HEADERS) (CONTENT OBJECT)) :DOCUMENTATION \"Send `content' as an HTTP 1.0 request on `stream' using `method'.\nThe request is sent to `url-path' at `host'. The `stream' must be a TCP-stream\nthat is connected to `host' at the appropriate port. `content' can be a string or\nan input stream to read from.\" :PUBLIC? TRUE)", Native.find_java_method("edu.isi.webtools.http.Http", "writeHttpRequest", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.OutputStream"), Native.find_java_class("edu.isi.stella.Keyword"), Native.find_java_class("java.lang.String"), Native.find_java_class("java.lang.String"), Native.find_java_class("edu.isi.stella.KeyValueList"), Native.find_java_class("edu.isi.stella.Stella_Object")}), null); Stella.defineFunctionObject("HTTP-POST-DATA", "(DEFUN (HTTP-POST-DATA INPUT-STREAM) ((HOST STRING) (PORT INTEGER) (URL-PATH STRING) (HEADERS HTTP-HEADERS) (CONTENT OBJECT)) :DOCUMENTATION \"Posts `content' as data to `url-path' on `host' and `port'.\n`content' can be a string or an input stream to read from. The port value for\nstandard http servers is 80. Returns the body of the reply message as a stream,\nif successful. Otherwise an HTTP-EXCEPTION is signaled.\" :PUBLIC? TRUE)", Native.find_java_method("edu.isi.webtools.http.Http", "httpPostData", new java.lang.Class [] {Native.find_java_class("java.lang.String"), java.lang.Integer.TYPE, Native.find_java_class("java.lang.String"), Native.find_java_class("edu.isi.stella.KeyValueList"), Native.find_java_class("edu.isi.stella.Stella_Object")}), null); Stella.defineFunctionObject("HTTP-POST-DATA-TO-STRING", "(DEFUN (HTTP-POST-DATA-TO-STRING STRING) ((HOST STRING) (PORT INTEGER) (URL-PATH STRING) (HEADERS HTTP-HEADERS) (CONTENT OBJECT)) :DOCUMENTATION \"Just like `http-post-data' (which see) but returns the reply as a string.\nCAUTION: String conversion will not do the right thing for binary data in Java.\" :PUBLIC? TRUE)", Native.find_java_method("edu.isi.webtools.http.Http", "httpPostDataToString", new java.lang.Class [] {Native.find_java_class("java.lang.String"), java.lang.Integer.TYPE, Native.find_java_class("java.lang.String"), Native.find_java_class("edu.isi.stella.KeyValueList"), Native.find_java_class("edu.isi.stella.Stella_Object")}), null); Stella.defineFunctionObject("HTTP-GET-DATA", "(DEFUN (HTTP-GET-DATA INPUT-STREAM) ((HOST STRING) (PORT INTEGER) (URL-PATH STRING) (RETURN-HEADERS HTTP-HEADERS)) :DOCUMENTATION \"Accesses the data described by `url-path' on `host' and `port'.\nThe port value for standard http servers is 80. If successful, returns the body\nof the web message as a stream. The headers from the reply message will be set\nin `return-headers' if not null'. If an error occurs an HTTP-EXCEPTION is signaled.\" :PUBLIC? TRUE)", Native.find_java_method("edu.isi.webtools.http.Http", "httpGetData", new java.lang.Class [] {Native.find_java_class("java.lang.String"), java.lang.Integer.TYPE, Native.find_java_class("java.lang.String"), Native.find_java_class("edu.isi.stella.KeyValueList")}), null); Stella.defineFunctionObject("HTTP-GET-DATA-TO-STRING", "(DEFUN (HTTP-GET-DATA-TO-STRING STRING) ((HOST STRING) (PORT INTEGER) (URL-PATH STRING) (RETURN-HEADERS HTTP-HEADERS)) :DOCUMENTATION \"Just like `http-get-data' (which see) but returns the result as a string.\nCAUTION: String conversion will not do the right thing for binary data in Java.\" :PUBLIC? TRUE)", Native.find_java_method("edu.isi.webtools.http.Http", "httpGetDataToString", new java.lang.Class [] {Native.find_java_class("java.lang.String"), java.lang.Integer.TYPE, Native.find_java_class("java.lang.String"), Native.find_java_class("edu.isi.stella.KeyValueList")}), null); Stella.defineFunctionObject("OPEN-URL-STREAM", "(DEFUN (OPEN-URL-STREAM INPUT-STREAM) ((URL STRING)) :DOCUMENTATION \"Opens an input stream to `url'.\nCurrently only http: with no user name or password and file: urls on the local\nhost with absolute pathnames are supported.\" :PUBLIC? TRUE)", Native.find_java_method("edu.isi.webtools.http.Http", "openUrlStream", new java.lang.Class [] {Native.find_java_class("java.lang.String")}), null); Stella.defineFunctionObject("WITH-INPUT-URL", "(DEFUN WITH-INPUT-URL ((BINDING CONS) |&BODY| (BODY CONS)) :TYPE OBJECT :MACRO? TRUE :DOCUMENTATION \"Sets up an unwind-protected form which opens a URL for\ninput and closes it afterwards. The stream for reading is bound to the\nvariable provided in the macro form.\nSyntax is `(WITH-INPUT-URL (var url) body+)'.\" :PUBLIC? TRUE)", Native.find_java_method("edu.isi.webtools.http.Http", "withInputUrl", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Cons"), Native.find_java_class("edu.isi.stella.Cons")}), null); Stella.defineFunctionObject("DOWNLOAD-URL", "(DEFUN DOWNLOAD-URL ((URL STRING) (FILE STRING)) :DOCUMENTATION \"Download the data at `url' and save it to `file'.\" :PUBLIC? TRUE :COMMAND? TRUE)", Native.find_java_method("edu.isi.webtools.http.Http", "downloadUrl", new java.lang.Class [] {Native.find_java_class("java.lang.String"), Native.find_java_class("java.lang.String")}), Native.find_java_method("edu.isi.webtools.http.Http", "downloadUrlEvaluatorWrapper", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Cons")})); Stella.defineFunctionObject("DOWNLOAD-URL-TO-STRING", "(DEFUN (DOWNLOAD-URL-TO-STRING STRING) ((URL STRING)) :DOCUMENTATION \"Download the data at `url' and return it as a string.\nCAUTION: String conversion will not do the right thing for binary data in Java.\" :PUBLIC? TRUE :COMMAND? TRUE)", Native.find_java_method("edu.isi.webtools.http.Http", "downloadUrlToString", new java.lang.Class [] {Native.find_java_class("java.lang.String")}), Native.find_java_method("edu.isi.webtools.http.Http", "downloadUrlToStringEvaluatorWrapper", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Cons")})); Stella.defineFunctionObject("DO-HTTP-REQUEST", "(DEFUN (DO-HTTP-REQUEST STRING) ((URI STRING) |&REST| (OPTIONS OBJECT)) :DOCUMENTATION \"Send an http request to `uri' and return a string representing the result.\" :PUBLIC? TRUE :COMMAND? TRUE)", Native.find_java_method("edu.isi.webtools.http.Http", "doHttpRequest", new java.lang.Class [] {Native.find_java_class("java.lang.String"), Native.find_java_class("edu.isi.stella.Cons")}), Native.find_java_method("edu.isi.webtools.http.Http", "doHttpRequestEvaluatorWrapper", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Cons")})); Stella.defineFunctionObject("STARTUP-HTTP-CLIENT", "(DEFUN STARTUP-HTTP-CLIENT () :PUBLIC? TRUE)", Native.find_java_method("edu.isi.webtools.http._StartupHttpClient", "startupHttpClient", new java.lang.Class [] {}), null); { MethodSlot function = Symbol.lookupFunction(Http.SYM_HTTP_STARTUP_HTTP_CLIENT); KeyValueList.setDynamicSlotValue(function.dynamicSlots, Http.SYM_STELLA_METHOD_STARTUP_CLASSNAME, StringWrapper.wrapString("_StartupHttpClient"), Stella.NULL_STRING_WRAPPER); } } if (Stella.currentStartupTimePhaseP(8)) { Stella.finalizeSlots(); Stella.cleanupUnfinalizedClasses(); } if (Stella.currentStartupTimePhaseP(9)) { Stella_Object.inModule(((StringWrapper)(Stella_Object.copyConsTree(StringWrapper.wrapString("HTTP"))))); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFCONSTANT HTTP-DEFAULT-PORT INTEGER 80)"); } } finally { Stella.$CONTEXT$.set(old$Context$000); Stella.$MODULE$.set(old$Module$000); } } }
6
private boolean goalIsOnTheRoad(Goal goal) { Direction cabinDirection = cabinDirection(); if (cabinDirection == Direction.DOWN) { return cabin.getCurrentFloor() >= goal.getFloor() && goal.getFloor() >= nextFloorToReach() && Direction.DOWN == goal.getNextDirection(); } return cabin.getCurrentFloor() <= goal.getFloor() && goal.getFloor() <= nextFloorToReach() && Direction.UP == goal.getNextDirection(); }
5
@Override public boolean tick(Tickable ticking, int tickID) { if(!super.tick(ticking,tickID)) return false; if((affected instanceof MOB) &&(((MOB)affected).isInCombat()) &&(!struckDownToday) &&(CMLib.dice().roll(1,1000,0)==1) &&(((MOB)affected).getWorshipCharID().length()>0) &&(!((MOB)affected).getVictim().getWorshipCharID().equals(((MOB)affected).getWorshipCharID()))) { final MOB deityM=CMLib.map().getDeity(((MOB)affected).getWorshipCharID()); if(deityM!=null) { struckDownToday=true; ((MOB)affected).location().showOthers(deityM,((MOB)affected).getVictim(),null,CMMsg.MSG_OK_ACTION,L("@x1 strike(s) down <T-NAME> with all of <S-HIS-HER> divine fury!",deityM.name())); CMLib.combat().postDeath(deityM,((MOB)affected).getVictim(),null); } } return true; }
8
@Override public boolean contains(Object o){ if(o instanceof Set<?>){ Set<?> set = (Set<?>) o; if(wrapped.containsAll(set)){ return true; } } return false; }
5
private void drawDragRowInsertionMarker(Graphics gc, Row parent, int insertAtIndex) { Rectangle bounds = getDragRowInsertionMarkerBounds(parent, insertAtIndex); gc.setColor(Color.red); gc.drawLine(bounds.x, bounds.y + bounds.height / 2, bounds.x + bounds.width, bounds.y + bounds.height / 2); for (int i = 0; i < bounds.height / 2; i++) { gc.drawLine(bounds.x + i, bounds.y + i, bounds.x + i, bounds.y + bounds.height - (1 + i)); } }
1
protected void spots(int i, int j, BufferedImage completePic, int toSpread) { // 10% chance to stop, 90% chance to keep going on each iteration for (double rand = random.nextDouble(); rand < 0.9; rand = random .nextDouble()) { if (rand < 0.225) { i--; } else if (rand < 0.450) { i++; } else if (rand < 0.675) { j--; } else { j++; } if (inBounds(i, j, completePic) && completedPixels[i][j] == false) { completePic.setRGB(i, j, toSpread); completedPixels[i][j] = true; } } }
6
public boolean isAABBInMaterial(AxisAlignedBB par1AxisAlignedBB, Material par2Material) { int var3 = MathHelper.floor_double(par1AxisAlignedBB.minX); int var4 = MathHelper.floor_double(par1AxisAlignedBB.maxX + 1.0D); int var5 = MathHelper.floor_double(par1AxisAlignedBB.minY); int var6 = MathHelper.floor_double(par1AxisAlignedBB.maxY + 1.0D); int var7 = MathHelper.floor_double(par1AxisAlignedBB.minZ); int var8 = MathHelper.floor_double(par1AxisAlignedBB.maxZ + 1.0D); for (int var9 = var3; var9 < var4; ++var9) { for (int var10 = var5; var10 < var6; ++var10) { for (int var11 = var7; var11 < var8; ++var11) { Block var12 = Block.blocksList[this.getBlockId(var9, var10, var11)]; if (var12 != null && var12.blockMaterial == par2Material) { int var13 = this.getBlockMetadata(var9, var10, var11); double var14 = (double)(var10 + 1); if (var13 < 8) { var14 = (double)(var10 + 1) - (double)var13 / 8.0D; } if (var14 >= par1AxisAlignedBB.minY) { return true; } } } } } return false; }
7
public void keyPressed(int k){ if(k == KeyEvent.VK_RIGHT) player.setRight(true); if(k == KeyEvent.VK_LEFT) player.setLeft(true); if(k == KeyEvent.VK_W) player.setJumping(true); if(k == KeyEvent.VK_R) player.setScratching(); if(k == KeyEvent.VK_F) player.setFiring(); }
5
public static int stringToInt(String s) throws IllegalArgumentException { /* * (1) Determine if number should be negative (and starting index for * processing the rest of the String. */ boolean isNegative = false; if (s.length() > 1 && s.charAt(0) == '-') { isNegative = true; } /* * (2) Iterate over all characters of the string, and construct the resulting * number; if any of the characters is not a digit, throw Exception */ int x = 0; for (int i = (isNegative?1:0); i < s.length(); i++) { Character c = s.charAt(i); if (Character.isDigit(c)) { x = x * 10 + Integer.valueOf(c) - '0'; }else { throw new IllegalArgumentException(); } } if (isNegative) { x = -x; } return x; }
6
@Override public boolean push_msg (Msg msg_) { switch (state) { case bottom: if (msg_.flags () == Msg.more && msg_.size () == 0) { state = State.body; return super.push_msg (msg_); } break; case body: if (msg_.flags () == Msg.more) return super.push_msg (msg_); if (msg_.flags () == 0) { state = State.bottom; return super.push_msg (msg_); } break; case identity: if (msg_.flags () == 0) { state = State.bottom; return super.push_msg (msg_); } break; } throw new IllegalStateException(state.toString()); }
8
public ClassInfo loadClass(final String name) throws ClassNotFoundException { final String classFileName = name.replace('.', '/') + ".class"; final InputStream is = BloatingClassLoader.this .getResourceAsStream(classFileName); if (is == null) { throw new ClassNotFoundException("Could not find class " + name); } final DataInputStream dis = new DataInputStream(is); return new ClassFile(null, this, dis); }
1
public List findAll() { log.debug("finding all Member instances"); try { String queryString = "from Member"; Query queryObject = getSession().createQuery(queryString); return queryObject.list(); } catch (RuntimeException re) { log.error("find all failed", re); throw re; } }
1
public void testFormat_shortBasicParse() { // Tests special two digit parse to make sure it properly switches // between lenient and strict parsing. DateTime dt = new DateTime(2004, 3, 9, 0, 0, 0, 0); DateTimeFormatter f = DateTimeFormat.forPattern("yyMMdd"); assertEquals(dt, f.parseDateTime("040309")); try { assertEquals(dt, f.parseDateTime("20040309")); fail(); } catch (IllegalArgumentException ex) {} f = DateTimeFormat.forPattern("yy/MM/dd"); assertEquals(dt, f.parseDateTime("04/03/09")); assertEquals(dt, f.parseDateTime("2004/03/09")); }
1
public static void llenarMemorizacion2() { for (int i = 0; i < matriz.length; i++) { for (int j = 0; j < matriz[0].length; j++) { int cuento = (matriz[i][j]=='.'? 1:0 ); if(i==0 && j==0) memorizacion2[i][j] = cuento; else if(i==0) memorizacion2[i][j] = memorizacion2[i][j-1] + cuento; else if(j==0) memorizacion2[i][j] = memorizacion2[i-1][j] + cuento; else memorizacion2[i][j] = memorizacion2[i-1][j]+memorizacion2[i][j-1]-memorizacion2[i-1][j-1]+cuento; } } }
7
public int getDepth() { return depth; }
0
public Meta(HtmlMidNode parent, HtmlAttributeToken[] attrs){ super(parent, attrs); for(HtmlAttributeToken attr:attrs){ String v = attr.getAttrValue(); switch(attr.getAttrName()){ case "charset": charset = Charset.parse(this, v); break; case "content": content = Content.parse(this, v); break; case "httpequiv": httpequiv = Httpequiv.parse(this, v); break; case "name": name = Name.parse(this, v); break; case "scheme": scheme = Scheme.parse(this, v); break; } } }
6
public static int getPalindromeLength(String str) { // 1.构造新的字符串 // 为了避免奇数回文和偶数回文的不同处理问题,在原字符串中插入'#',将所有回文变成奇数回文 StringBuilder newStr = new StringBuilder(); newStr.append('#'); for (int i = 0; i < str.length(); i++) { newStr.append(str.charAt(i)); newStr.append('#'); } // rad[i]表示以i为中心的回文的最大半径,i至少为1,即该字符本身 int[] rad = new int[newStr.length()]; // right表示已知的回文中,最右的边界的坐标 int right = -1; // id表示已知的回文中,拥有最右边界的回文的中点坐标 int id = -1; // 2.计算所有的rad // 这个算法是O(n)的,因为right只会随着里层while的迭代而增长,不会减少。 for (int i = 0; i < newStr.length(); i++) { // 2.1.确定一个最小的半径 int r = 1; if (i <= right) { r = Math.min(rad[id] - i + id, rad[2 * id - i]); } // 2.2.尝试更大的半径 while (i - r >= 0 && i + r < newStr.length() && newStr.charAt(i - r) == newStr.charAt(i + r)) { r++; } // 2.3.更新边界和回文中心坐标 if (i + r - 1 > right) { right = i + r - 1; id = i; } rad[i] = r; } // 3.扫描一遍rad数组,找出最大的半径 int maxLength = 0; int centerIndex = 0; for (int i = 0; i < rad.length; i++) { if (rad[i] > maxLength) { maxLength = rad[i]; centerIndex = i; } } System.out.println(str.substring((centerIndex - maxLength) / 2 + 1, maxLength + 1)); return maxLength - 1; }
9
public static void berakning(int m, int n, int[] NtoY, int[] XtoM, int[][] vagar) { int min = vagar[0][0] + XtoM[0] + NtoY[0]; String Zon = "station 1 och station 1. Vilket är på avståndet: " + min + "."; for(int i = 0; i < m; i++) { for(int i2 = 0; i2 < n; i2++) { int kortvag = vagar[i][i2] + XtoM[i] + NtoY[i2]; System.out.println("Station " + (i+1) + " och station " + (i2+1) + ". Avståndet: " + kortvag); if(kortvag < min) { min = kortvag; Zon = "station " + (i+1) + " och station " + (i2+1) + ". Vilket är på avståndet " + min + "."; } } System.out.println(); } System.out.println( "Avstånd från X till M: " + Arrays.toString(XtoM) + "\nAvstånd från Y till N: " + Arrays.toString(NtoY) + "\nAntal stationer i första zonen: " + m + "\nAntal stationer i andra zonen: " + n + "\nKortaste vägen från X till Y är genom " + Zon ); }
3
protected void setSourceDragColumn(TreeColumn column) { if (mSourceDragColumn != null) { repaintColumn(mSourceDragColumn); } mSourceDragColumn = column; if (mSourceDragColumn != null) { repaintColumn(mSourceDragColumn); } }
2
public static void startupTimepointSupport() { { Object old$Module$000 = Stella.$MODULE$.get(); Object old$Context$000 = Stella.$CONTEXT$.get(); try { Native.setSpecial(Stella.$MODULE$, Stella.getStellaModule("/TIMEPOINT-SUPPORT", Stella.$STARTUP_TIME_PHASE$ > 1)); Native.setSpecial(Stella.$CONTEXT$, ((Module)(Stella.$MODULE$.get()))); if (Stella.currentStartupTimePhaseP(2)) { Timepoint.SGT_TIMEPOINT_KB_TIMEPOINT_OF = ((Surrogate)(GeneralizedSymbol.internRigidSymbolWrtModule("TIMEPOINT-OF", Stella.getStellaModule("/TIMEPOINT-KB", true), 1))); Timepoint.SGT_TIMEPOINT_KB_DURATION_OF = ((Surrogate)(GeneralizedSymbol.internRigidSymbolWrtModule("DURATION-OF", Stella.getStellaModule("/TIMEPOINT-KB", true), 1))); Timepoint.SYM_TIMEPOINT_SUPPORT_TIMEPOINT_OF$_COMPUTATION = ((Symbol)(GeneralizedSymbol.internRigidSymbolWrtModule("TIMEPOINT-OF*-COMPUTATION", null, 0))); Timepoint.KWD_MONDAY = ((Keyword)(GeneralizedSymbol.internRigidSymbolWrtModule("MONDAY", null, 2))); Timepoint.SGT_TIMEPOINT_KB_MONDAY = ((Surrogate)(GeneralizedSymbol.internRigidSymbolWrtModule("MONDAY", Stella.getStellaModule("/TIMEPOINT-KB", true), 1))); Timepoint.KWD_TUESDAY = ((Keyword)(GeneralizedSymbol.internRigidSymbolWrtModule("TUESDAY", null, 2))); Timepoint.SGT_TIMEPOINT_KB_TUESDAY = ((Surrogate)(GeneralizedSymbol.internRigidSymbolWrtModule("TUESDAY", Stella.getStellaModule("/TIMEPOINT-KB", true), 1))); Timepoint.KWD_WEDNESDAY = ((Keyword)(GeneralizedSymbol.internRigidSymbolWrtModule("WEDNESDAY", null, 2))); Timepoint.SGT_TIMEPOINT_KB_WEDNESDAY = ((Surrogate)(GeneralizedSymbol.internRigidSymbolWrtModule("WEDNESDAY", Stella.getStellaModule("/TIMEPOINT-KB", true), 1))); Timepoint.KWD_THURSDAY = ((Keyword)(GeneralizedSymbol.internRigidSymbolWrtModule("THURSDAY", null, 2))); Timepoint.SGT_TIMEPOINT_KB_THURSDAY = ((Surrogate)(GeneralizedSymbol.internRigidSymbolWrtModule("THURSDAY", Stella.getStellaModule("/TIMEPOINT-KB", true), 1))); Timepoint.KWD_FRIDAY = ((Keyword)(GeneralizedSymbol.internRigidSymbolWrtModule("FRIDAY", null, 2))); Timepoint.SGT_TIMEPOINT_KB_FRIDAY = ((Surrogate)(GeneralizedSymbol.internRigidSymbolWrtModule("FRIDAY", Stella.getStellaModule("/TIMEPOINT-KB", true), 1))); Timepoint.KWD_SATURDAY = ((Keyword)(GeneralizedSymbol.internRigidSymbolWrtModule("SATURDAY", null, 2))); Timepoint.SGT_TIMEPOINT_KB_SATURDAY = ((Surrogate)(GeneralizedSymbol.internRigidSymbolWrtModule("SATURDAY", Stella.getStellaModule("/TIMEPOINT-KB", true), 1))); Timepoint.KWD_SUNDAY = ((Keyword)(GeneralizedSymbol.internRigidSymbolWrtModule("SUNDAY", null, 2))); Timepoint.SGT_TIMEPOINT_KB_SUNDAY = ((Surrogate)(GeneralizedSymbol.internRigidSymbolWrtModule("SUNDAY", Stella.getStellaModule("/TIMEPOINT-KB", true), 1))); Timepoint.SYM_TIMEPOINT_SUPPORT_STARTUP_TIMEPOINT_SUPPORT = ((Symbol)(GeneralizedSymbol.internRigidSymbolWrtModule("STARTUP-TIMEPOINT-SUPPORT", null, 0))); } if (Stella.currentStartupTimePhaseP(4)) { Timepoint.$DATE_TIME_HASH_TABLE$ = StellaHashTable.newStellaHashTable(); } if (Stella.currentStartupTimePhaseP(5)) { { Stella_Class renamed_Class = Stella.defineClassFromStringifiedSource("DATE-TIME-LOGIC-WRAPPER", "(DEFCLASS DATE-TIME-LOGIC-WRAPPER (QUANTITY-LOGIC-WRAPPER) :PUBLIC-SLOTS ((WRAPPER-VALUE :TYPE DATE-TIME-OBJECT :REQUIRED? TRUE)) :PRINT-FORM (IF *PRINTREADABLY?* (PRINT-NATIVE-STREAM STREAM (WRAPPER-VALUE SELF)) (PRINT-NATIVE-STREAM STREAM \"|tw|\" (WRAPPER-VALUE SELF))))"); renamed_Class.classConstructorCode = Native.find_java_method("edu.isi.powerloom.extensions.timepoint.DateTimeLogicWrapper", "newDateTimeLogicWrapper", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.DateTimeObject")}); renamed_Class.classSlotAccessorCode = Native.find_java_method("edu.isi.powerloom.extensions.timepoint.DateTimeLogicWrapper", "accessDateTimeLogicWrapperSlotValue", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.extensions.timepoint.DateTimeLogicWrapper"), 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)) { Stella.defineMethodObject("(DEFMETHOD (GENERATE-SPECIALIZED-TERM OBJECT) ((SELF DATE-TIME-LOGIC-WRAPPER)))", Native.find_java_method("edu.isi.powerloom.extensions.timepoint.DateTimeLogicWrapper", "generateSpecializedTerm", new java.lang.Class [] {}), ((java.lang.reflect.Method)(null))); Stella.defineMethodObject("(DEFMETHOD (HASH-CODE INTEGER) ((SELF DATE-TIME-LOGIC-WRAPPER)))", Native.find_java_method("edu.isi.powerloom.extensions.timepoint.DateTimeLogicWrapper", "hashCode_", new java.lang.Class [] {}), ((java.lang.reflect.Method)(null))); Stella.defineMethodObject("(DEFMETHOD (OBJECT-EQL? BOOLEAN) ((SELF DATE-TIME-LOGIC-WRAPPER) (X OBJECT)))", Native.find_java_method("edu.isi.powerloom.extensions.timepoint.DateTimeLogicWrapper", "objectEqlP", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Stella_Object")}), ((java.lang.reflect.Method)(null))); Stella.defineFunctionObject("WRAP-DATE-TIME", "(DEFUN (WRAP-DATE-TIME DATE-TIME-LOGIC-WRAPPER) ((VALUE DATE-TIME-OBJECT)) :PUBLIC? TRUE :DOCUMENTATION \"Return an interned LOGIC-WRAPPER for `value'. This assures us\nthat all logic-wrapped DATE-TIME-OBJECTs are the same object.\")", Native.find_java_method("edu.isi.powerloom.extensions.timepoint.Timepoint", "wrapDateTime", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.DateTimeObject")}), null); Stella.defineFunctionObject("HELP-GET-CALENDAR-TIME", "(DEFUN (HELP-GET-CALENDAR-TIME DATE-TIME-LOGIC-WRAPPER) ((ITEM OBJECT)))", Native.find_java_method("edu.isi.powerloom.extensions.timepoint.Timepoint", "helpGetCalendarTime", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Stella_Object")}), null); Stella.defineFunctionObject("HELP-GET-TIME-DURATION", "(DEFUN (HELP-GET-TIME-DURATION DATE-TIME-LOGIC-WRAPPER) ((ITEM OBJECT)))", Native.find_java_method("edu.isi.powerloom.extensions.timepoint.Timepoint", "helpGetTimeDuration", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Stella_Object")}), null); Stella.defineFunctionObject("HELP-GET-TIME-OBJECT", "(DEFUN (HELP-GET-TIME-OBJECT DATE-TIME-LOGIC-WRAPPER) ((ITEM OBJECT)))", Native.find_java_method("edu.isi.powerloom.extensions.timepoint.Timepoint", "helpGetTimeObject", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Stella_Object")}), null); Stella.defineFunctionObject("HELP-GET-INTEGER", "(DEFUN (HELP-GET-INTEGER INTEGER) ((OBJ OBJECT)))", Native.find_java_method("edu.isi.powerloom.extensions.timepoint.Timepoint", "helpGetInteger", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Stella_Object")}), null); Stella.defineFunctionObject("HELP-GET-FLOAT", "(DEFUN (HELP-GET-FLOAT FLOAT) ((OBJ OBJECT)))", Native.find_java_method("edu.isi.powerloom.extensions.timepoint.Timepoint", "helpGetFloat", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Stella_Object")}), null); Stella.defineFunctionObject("HELP-GET-TIMEZONE", "(DEFUN (HELP-GET-TIMEZONE FLOAT) ((OBJ OBJECT)))", Native.find_java_method("edu.isi.powerloom.extensions.timepoint.Timepoint", "helpGetTimezone", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Stella_Object")}), null); Stella.defineFunctionObject("CAN-BIND-ALL?", "(DEFUN (CAN-BIND-ALL? BOOLEAN) ((PL-OBJECTS CONS) (VALUES CONS)))", Native.find_java_method("edu.isi.powerloom.extensions.timepoint.Timepoint", "canBindAllP", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Cons"), Native.find_java_class("edu.isi.stella.Cons")}), null); Stella.defineFunctionObject("TIMEPOINT-OF-CONSTRAINT", "(DEFUN (TIMEPOINT-OF-CONSTRAINT OBJECT) ((MISSING-ARGUMENT INTEGER-WRAPPER) (X1 STRING-WRAPPER) (X2 DATE-TIME-LOGIC-WRAPPER)))", Native.find_java_method("edu.isi.powerloom.extensions.timepoint.Timepoint", "timepointOfConstraint", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.IntegerWrapper"), Native.find_java_class("edu.isi.stella.StringWrapper"), Native.find_java_class("edu.isi.powerloom.extensions.timepoint.DateTimeLogicWrapper")}), null); Stella.defineFunctionObject("TIMEPOINT-OF*-COMPUTATION", "(DEFUN (TIMEPOINT-OF*-COMPUTATION DATE-TIME-LOGIC-WRAPPER) ((YY INTEGER-WRAPPER) (MM INTEGER-WRAPPER) (DD INTEGER-WRAPPER) (HR INTEGER-WRAPPER) (MIN INTEGER-WRAPPER) (SEC NUMBER-WRAPPER) (TZ OBJECT)))", Native.find_java_method("edu.isi.powerloom.extensions.timepoint.Timepoint", "timepointOf$Computation", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.IntegerWrapper"), Native.find_java_class("edu.isi.stella.IntegerWrapper"), Native.find_java_class("edu.isi.stella.IntegerWrapper"), Native.find_java_class("edu.isi.stella.IntegerWrapper"), Native.find_java_class("edu.isi.stella.IntegerWrapper"), Native.find_java_class("edu.isi.stella.NumberWrapper"), Native.find_java_class("edu.isi.stella.Stella_Object")}), null); Stella.defineFunctionObject("TIMEPOINT-OF*-EVALUATOR", "(DEFUN TIMEPOINT-OF*-EVALUATOR ((SELF PROPOSITION)))", Native.find_java_method("edu.isi.powerloom.extensions.timepoint.Timepoint", "timepointOf$Evaluator", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.Proposition")}), null); Stella.defineFunctionObject("TIMEPOINT-OF*-SPECIALIST", "(DEFUN (TIMEPOINT-OF*-SPECIALIST KEYWORD) ((FRAME CONTROL-FRAME) (LASTMOVE KEYWORD)))", Native.find_java_method("edu.isi.powerloom.extensions.timepoint.Timepoint", "timepointOf$Specialist", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.ControlFrame"), Native.find_java_class("edu.isi.stella.Keyword")}), null); Stella.defineFunctionObject("DURATION-OF-CONSTRAINT", "(DEFUN (DURATION-OF-CONSTRAINT OBJECT) ((MISSING-ARGUMENT INTEGER-WRAPPER) (X1 STRING-WRAPPER) (X2 DATE-TIME-LOGIC-WRAPPER)))", Native.find_java_method("edu.isi.powerloom.extensions.timepoint.Timepoint", "durationOfConstraint", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.IntegerWrapper"), Native.find_java_class("edu.isi.stella.StringWrapper"), Native.find_java_class("edu.isi.powerloom.extensions.timepoint.DateTimeLogicWrapper")}), null); Stella.defineFunctionObject("TIME-MINUS-CONSTRAINT", "(DEFUN (TIME-MINUS-CONSTRAINT OBJECT) ((MISSING-ARGUMENT INTEGER-WRAPPER) (X1 DATE-TIME-LOGIC-WRAPPER) (X2 DATE-TIME-LOGIC-WRAPPER) (X3 DATE-TIME-LOGIC-WRAPPER)))", Native.find_java_method("edu.isi.powerloom.extensions.timepoint.Timepoint", "timeMinusConstraint", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.IntegerWrapper"), Native.find_java_class("edu.isi.powerloom.extensions.timepoint.DateTimeLogicWrapper"), Native.find_java_class("edu.isi.powerloom.extensions.timepoint.DateTimeLogicWrapper"), Native.find_java_class("edu.isi.powerloom.extensions.timepoint.DateTimeLogicWrapper")}), null); Stella.defineFunctionObject("TIME-PLUS-CONSTRAINT", "(DEFUN (TIME-PLUS-CONSTRAINT OBJECT) ((MISSING-ARGUMENT INTEGER-WRAPPER) (X1 DATE-TIME-LOGIC-WRAPPER) (X2 DATE-TIME-LOGIC-WRAPPER) (X3 DATE-TIME-LOGIC-WRAPPER)))", Native.find_java_method("edu.isi.powerloom.extensions.timepoint.Timepoint", "timePlusConstraint", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.IntegerWrapper"), Native.find_java_class("edu.isi.powerloom.extensions.timepoint.DateTimeLogicWrapper"), Native.find_java_class("edu.isi.powerloom.extensions.timepoint.DateTimeLogicWrapper"), Native.find_java_class("edu.isi.powerloom.extensions.timepoint.DateTimeLogicWrapper")}), null); Stella.defineFunctionObject("HELP-GET-TIME-ZONE", "(DEFUN (HELP-GET-TIME-ZONE FLOAT) ((TIME-ZONE-SPECIFIER OBJECT)))", Native.find_java_method("edu.isi.powerloom.extensions.timepoint.Timepoint", "helpGetTimeZone", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Stella_Object")}), null); Stella.defineFunctionObject("DOW-KEYWORD-TO-INSTANCE", "(DEFUN (DOW-KEYWORD-TO-INSTANCE LOGIC-OBJECT) ((DOW KEYWORD)))", Native.find_java_method("edu.isi.powerloom.extensions.timepoint.Timepoint", "dowKeywordToInstance", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Keyword")}), null); Stella.defineFunctionObject("TIMEPOINT-YEAR-COMPUTATION", "(DEFUN (TIMEPOINT-YEAR-COMPUTATION INTEGER-WRAPPER) ((TIMEPOINT DATE-TIME-LOGIC-WRAPPER) (TIMEZONE OBJECT)))", Native.find_java_method("edu.isi.powerloom.extensions.timepoint.DateTimeLogicWrapper", "timepointYearComputation", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.extensions.timepoint.DateTimeLogicWrapper"), Native.find_java_class("edu.isi.stella.Stella_Object")}), null); Stella.defineFunctionObject("TIMEPOINT-MONTH-COMPUTATION", "(DEFUN (TIMEPOINT-MONTH-COMPUTATION INTEGER-WRAPPER) ((TIMEPOINT DATE-TIME-LOGIC-WRAPPER) (TIMEZONE OBJECT)))", Native.find_java_method("edu.isi.powerloom.extensions.timepoint.DateTimeLogicWrapper", "timepointMonthComputation", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.extensions.timepoint.DateTimeLogicWrapper"), Native.find_java_class("edu.isi.stella.Stella_Object")}), null); Stella.defineFunctionObject("TIMEPOINT-DAY-COMPUTATION", "(DEFUN (TIMEPOINT-DAY-COMPUTATION INTEGER-WRAPPER) ((TIMEPOINT DATE-TIME-LOGIC-WRAPPER) (TIMEZONE OBJECT)))", Native.find_java_method("edu.isi.powerloom.extensions.timepoint.DateTimeLogicWrapper", "timepointDayComputation", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.extensions.timepoint.DateTimeLogicWrapper"), Native.find_java_class("edu.isi.stella.Stella_Object")}), null); Stella.defineFunctionObject("TIMEPOINT-DAY-OF-WEEK-COMPUTATION", "(DEFUN (TIMEPOINT-DAY-OF-WEEK-COMPUTATION LOGIC-OBJECT) ((TIMEPOINT DATE-TIME-LOGIC-WRAPPER) (TIMEZONE OBJECT)))", Native.find_java_method("edu.isi.powerloom.extensions.timepoint.DateTimeLogicWrapper", "timepointDayOfWeekComputation", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.extensions.timepoint.DateTimeLogicWrapper"), Native.find_java_class("edu.isi.stella.Stella_Object")}), null); Stella.defineFunctionObject("TIMEPOINT-HOUR-COMPUTATION", "(DEFUN (TIMEPOINT-HOUR-COMPUTATION INTEGER-WRAPPER) ((TIMEPOINT DATE-TIME-LOGIC-WRAPPER) (TIMEZONE OBJECT)))", Native.find_java_method("edu.isi.powerloom.extensions.timepoint.DateTimeLogicWrapper", "timepointHourComputation", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.extensions.timepoint.DateTimeLogicWrapper"), Native.find_java_class("edu.isi.stella.Stella_Object")}), null); Stella.defineFunctionObject("TIMEPOINT-MINUTE-COMPUTATION", "(DEFUN (TIMEPOINT-MINUTE-COMPUTATION INTEGER-WRAPPER) ((TIMEPOINT DATE-TIME-LOGIC-WRAPPER) (TIMEZONE OBJECT)))", Native.find_java_method("edu.isi.powerloom.extensions.timepoint.DateTimeLogicWrapper", "timepointMinuteComputation", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.extensions.timepoint.DateTimeLogicWrapper"), Native.find_java_class("edu.isi.stella.Stella_Object")}), null); Stella.defineFunctionObject("TIMEPOINT-SECOND-COMPUTATION", "(DEFUN (TIMEPOINT-SECOND-COMPUTATION NUMBER-WRAPPER) ((TIMEPOINT DATE-TIME-LOGIC-WRAPPER) (TIMEZONE OBJECT)))", Native.find_java_method("edu.isi.powerloom.extensions.timepoint.DateTimeLogicWrapper", "timepointSecondComputation", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.extensions.timepoint.DateTimeLogicWrapper"), Native.find_java_class("edu.isi.stella.Stella_Object")}), null); Stella.defineFunctionObject("TIMEPOINT-DATE-COMPUTATION", "(DEFUN (TIMEPOINT-DATE-COMPUTATION STRING-WRAPPER) ((TIMEPOINT DATE-TIME-LOGIC-WRAPPER) (TIMEZONE OBJECT)))", Native.find_java_method("edu.isi.powerloom.extensions.timepoint.DateTimeLogicWrapper", "timepointDateComputation", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.extensions.timepoint.DateTimeLogicWrapper"), Native.find_java_class("edu.isi.stella.Stella_Object")}), null); Stella.defineFunctionObject("TIMEPOINT-TIME-COMPUTATION", "(DEFUN (TIMEPOINT-TIME-COMPUTATION STRING-WRAPPER) ((TIMEPOINT DATE-TIME-LOGIC-WRAPPER) (TIMEZONE OBJECT)))", Native.find_java_method("edu.isi.powerloom.extensions.timepoint.DateTimeLogicWrapper", "timepointTimeComputation", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.extensions.timepoint.DateTimeLogicWrapper"), Native.find_java_class("edu.isi.stella.Stella_Object")}), null); Stella.defineFunctionObject("STARTUP-TIMEPOINT-SUPPORT", "(DEFUN STARTUP-TIMEPOINT-SUPPORT () :PUBLIC? TRUE)", Native.find_java_method("edu.isi.powerloom.extensions.timepoint._StartupTimepointSupport", "startupTimepointSupport", new java.lang.Class [] {}), null); { MethodSlot function = Symbol.lookupFunction(Timepoint.SYM_TIMEPOINT_SUPPORT_STARTUP_TIMEPOINT_SUPPORT); KeyValueList.setDynamicSlotValue(function.dynamicSlots, edu.isi.powerloom.extensions.Extensions.SYM_STELLA_METHOD_STARTUP_CLASSNAME, StringWrapper.wrapString("_StartupTimepointSupport"), Stella.NULL_STRING_WRAPPER); } } if (Stella.currentStartupTimePhaseP(8)) { Stella.finalizeSlots(); Stella.cleanupUnfinalizedClasses(); } if (Stella.currentStartupTimePhaseP(9)) { Stella_Object.inModule(((StringWrapper)(Stella_Object.copyConsTree(StringWrapper.wrapString("TIMEPOINT-SUPPORT"))))); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *DATE-TIME-HASH-TABLE* (STELLA-HASH-TABLE OF DATE-TIME-OBJECT DATE-TIME-LOGIC-WRAPPER) (NEW STELLA-HASH-TABLE) :DOCUMENTATION \"Table for interning date-time logic wrappers\")"); } } finally { Stella.$CONTEXT$.set(old$Context$000); Stella.$MODULE$.set(old$Module$000); } } }
7
public void run() { /*if there is a message store and check it*/ if (bot.hasPrivateMessage()) { message = bot.getPrivateMessage(); } /*This method checks if the user has the proper access*/ if (checkAccess(2, bot.getPrivateSender()) == false) { return; } if (message.startsWith("~say")) { tokenize(true, 4, message); sendTo = (String) tokenParameters.nextElement(); while (tokenParameters.hasMoreElements()) { sendMessage += (String) tokenParameters.nextElement() + " "; } try { Main.bot.sendMessage(sendTo, sendMessage); } catch (NoSuchElementException e) { e.printStackTrace(); System.err.println("incorrect syntax"); } sendMessage = ""; } }
5
@EventHandler public void SpiderWaterBreathing(EntityDamageByEntityEvent event) { Entity e = event.getEntity(); Entity damager = event.getDamager(); String world = e.getWorld().getName(); boolean dodged = false; Random random = new Random(); double randomChance = plugin.getSpiderConfig().getDouble("Spider.WaterBreathing.DodgeChance") / 100; final double ChanceOfHappening = random.nextDouble(); if (ChanceOfHappening >= randomChance) { dodged = true; } if (plugin.getSpiderConfig().getBoolean("Spider.WaterBreathing.Enabled", true) && damager instanceof Spider && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) { Player player = (Player) e; player.addPotionEffect(new PotionEffect(PotionEffectType.WATER_BREATHING, plugin.getSpiderConfig().getInt("Spider.WaterBreathing.Time"), plugin.getSpiderConfig().getInt("Spider.WaterBreathing.Power"))); } }
6
public static void writeALevel(String level) throws Exception { System.out.println(level); BufferedReader reader = new BufferedReader(new FileReader(new File(ConfigReader.getMicrboesVsMetabolitesDir() + File.separator + "toFodor05182015_PL_shucha_bothLanes_wTaxa.txt"))); List<String> sampleNames = new ArrayList<String>(); String[] splits = reader.readLine().split("\t"); for( int x=1; x < splits.length - 1; x++) sampleNames.add(splits[x]); HashMap<String, List<Double>> map = new HashMap<String, List<Double>>(); for(String s = reader.readLine(); s != null; s= reader.readLine()) { splits = s.split("\t"); List<Double> thisList = new ArrayList<Double>(); for( int x=1; x < splits.length -1; x++) thisList.add(Double.parseDouble(splits[x])); String taxaString = splits[splits.length-1]; if( level.equals("otu")) taxaString = splits[0]; else taxaString = getAssignment(taxaString, level); List<Double> oldList = map.get(taxaString); if( oldList != null) { if( oldList.size() != thisList.size() ) throw new Exception("Logic error"); for( int x=0; x < oldList.size(); x++) { double newSum = oldList.get(x) + thisList.get(x); thisList.set(x, newSum); } } map.put(taxaString, thisList); } writeResults(sampleNames, map, level); }
7
public void save (String filepath) throws IOException { new ShrinkTail(tail,begs,lens).shrink(); int nodeSize = chck.size(); // 末尾の未使用部分を取り除く for(; nodeSize > 0 && chck.get(nodeSize-1) == Node.Chck.VACANT_CODE; nodeSize--); nodeSize += Node.Chck.CODE_LIMIT; // 検索時の範囲外アクセスを防ぐために、余白を設ける final int total = 4*3 + nodeSize*6 + begs.size()*6 + tail.length()*2; final FileMappedOutputStream fmos = new FileMappedOutputStream(filepath, total); try { fmos.putInt(nodeSize); fmos.putInt(begs.size()); fmos.putInt(tail.length()); // 4byte for(Integer n : begs) fmos.putInt(n); for(int i=0; i < nodeSize; i++) fmos.putInt(base.get(i, Node.Base.INIT_VALUE)); // 2byte for(Short n : lens) fmos.putShort(n); for(int i=0; i < nodeSize; i++) fmos.putChar(chck.get(i, Node.Chck.VACANT_CODE)); fmos.putString(tail.toString()); } finally { fmos.close(); } }
6
public static void main(String[] args) throws IOException { input(); output(); }
0
public Airplane() { wSeats=new String[TOTAL_WIN_SEATS]; aSeats=new String[TOTAL_AISLE_SEATS]; for(int i=0;i<wSeats.length;i++) { wSeats[i]=new String("NA"); } for(int i=0;i<wSeats.length;i++) { aSeats[i]=new String("NA"); } }
2
@Override public void executeMsg(final Environmental myHost, final CMMsg msg) { if((msg.source()==affected) &&(msg.sourceMinor()== CMMsg.TYP_FACTIONCHANGE) &&(msg.othersMessage()!=null) &&(msg.othersMessage().equalsIgnoreCase(CMLib.factions().AlignID())) &&(msg.value()>0) &&(msg.value()<Integer.MAX_VALUE)) { double prof; if((invoker()!=affected)&&(canBeUninvoked())) prof=super.getXLEVELLevel(invoker()); else prof=0; msg.setValue((int)Math.round(msg.value() * (0.5 - (prof*0.05)))); } super.executeMsg(myHost, msg); }
8
public void removeComponent(Class<? extends IComponent> clazz, Entity entity) { registeredComponents.get(clazz).remove(entity); }
1
public boolean load(String audiofile) { try { setFilename(audiofile); sample = AudioSystem.getAudioInputStream(getURL(filename)); clip.open(sample); return true; } catch (IOException e) { return false; } catch (UnsupportedAudioFileException e) { return false; } catch (LineUnavailableException e) { return false; } }
3
@EventHandler public void ZombieBlindness(EntityDamageByEntityEvent event) { Entity e = event.getEntity(); Entity damager = event.getDamager(); String world = e.getWorld().getName(); boolean dodged = false; Random random = new Random(); double randomChance = plugin.getZombieConfig().getDouble("Zombie.Blindness.DodgeChance") / 100; final double ChanceOfHappening = random.nextDouble(); if (ChanceOfHappening >= randomChance) { dodged = true; } if ( plugin.getZombieConfig().getBoolean("Zombie.Blindness.Enabled", true) && damager instanceof Zombie && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) { Player player = (Player) e; player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, plugin.getZombieConfig().getInt("Zombie.Blindness.Time"), plugin.getZombieConfig().getInt("Zombie.Blindness.Power"))); } }
6
private void enterIdSuccAndCost(ArrayList<PlageHoraire> PlagesHoraires, LinkedList<Livraison> tabLivraison, Tournee ens) throws Exception { PlageHoraire PH1,PH2; // Insert entrepot at the beginning ArrayList<Integer> suivantEntrepot = new ArrayList<>(); Livraison e = new Livraison(); e.setDestination(ens.getEntrepot()); e.setHorraire(PlagesHoraires.get(0)); dictionnaire.put(0,e); dictionnaireRetour.put(e,0); for(int i=1; i<nbVertices; i++) { PH1 = tabLivraison.get(i-1).getHoraire(); int indexPH1 = PlagesHoraires.indexOf(PH1); Livraison livr1 = tabLivraison.get(i-1); int noeud1 = livr1.getDestination().getId(); if((indexPH1 == 0)&&(noeud1 != ens.getEntrepot().getId())) { suivantEntrepot.add(i); Itineraire iti = new Itineraire(); iti.setPrevLivraison(e); iti.setNextLivraison(livr1); LinkedList<Troncon> ensembleTroncons = getPath(ens.getEntrepot().getId(),noeud1,ens.getPlan()); cost[0][i] = calculCost(ensembleTroncons); iti.setEnsembleTroncons(ensembleTroncons); ensembleTrajets.add(iti); setMinMax(cost[0][i]); } } succ.add(0,suivantEntrepot); // For each livraison minus entrepot int i; for(i=1; i<nbVertices; i++) { PH1 = tabLivraison.get(i-1).getHoraire(); int indexPH1 = PlagesHoraires.indexOf(PH1); Livraison livr1 = tabLivraison.get(i-1); int noeud1 = livr1.getDestination().getId(); ArrayList<Integer> l = new ArrayList<>(); int j; for(j=1; j<nbVertices; j++) { PH2 = tabLivraison.get(j-1).getHoraire(); int indexPH2 = PlagesHoraires.indexOf(PH2); Livraison livr2 = tabLivraison.get(j-1); int noeud2 = livr2.getDestination().getId(); // If duration of vertex2 is = or +1 of duration of vertex 1 -> enter in succ if((livr1 != livr2) && ((indexPH1 == indexPH2) || (indexPH2 == indexPH1+1))) { l.add(j); Itineraire iti = new Itineraire(); iti.setPrevLivraison(livr1); iti.setNextLivraison(livr2); LinkedList<Troncon> ensembleTroncons = getPath(noeud1,noeud2,ens.getPlan()); cost[i][j] = calculCost(ensembleTroncons); iti.setEnsembleTroncons(ensembleTroncons); ensembleTrajets.add(iti); setMinMax(cost[i][j]); } } // Insert entrepot at the end if(indexPH1 == PlagesHoraires.size()-1) { l.add(0); Itineraire iti = new Itineraire(); iti.setPrevLivraison(livr1); Livraison entrepot = new Livraison(); entrepot.setDestination(ens.getEntrepot()); entrepot.setHorraire(livr1.getHoraire()); iti.setNextLivraison(entrepot); LinkedList<Troncon> ensembleTroncons = getPath(noeud1,ens.getEntrepot().getId(),ens.getPlan()); cost[i][0] = calculCost(ensembleTroncons); iti.setEnsembleTroncons(ensembleTroncons); ensembleTrajets.add(iti); setMinMax(cost[i][0]); } succ.add(i,l); } }
9
private int countLivingNeighbors(int x, int y) { int livingNeighbors = 0; for (int xx = x - 1; xx < x + 2; xx++) { for (int yy = y - 1; yy < y + 2; yy++) { if (xx == x && yy == y) continue; if (isAlive(xx, yy)) { livingNeighbors++; } } } return livingNeighbors; }
5
private static int getJobBy5ByteEncoding(int encoded) { switch (encoded) { case 2: case 3: return 100; case 4: return 200; case 8: return 300; case 16: return 400; case 32: case 63: return 500; default: return 0; } }
7
@Override protected EntityManager getEntityManager() { return em; }
0
public final Function<Random, TestMethod> nextMethod(Class<?> actualType) { AliasedMethodTable<TestMethod> d = cache.get(requireNonNull(actualType)); return d != null ? d : cache.computeIfAbsent(actualType, new Function<Class<?>, AliasedMethodTable<TestMethod>>() { public AliasedMethodTable<TestMethod> apply(Class<?> at) { LinkedHashMap<TestMethod, Double> weights = new LinkedHashMap<>(); for (TestMethod rtm : TestMethodLoader.getTestsForType(at)) { double weight = calculateTestWeight(rtm); assertFalse(Double.isNaN(weight) || Double.isInfinite(weight)); if (weight > 0) { weights.put(rtm, weight); // System.out.println(rtm.toString2() + " " + weight); } } if (weights.isEmpty()) { throw new IllegalArgumentException( "All weights are 0 for targets of " + at.getCanonicalName() + " tm =" + TestMethodLoader.getTestsForType(at)); } return new AliasedMethodTable<>(weights); } }); }
8
private void heap_down() { Binarynode node = root; Binarynode help; int valuehelper; while (true) { if (node.right == null || node.left.value > node.right.value) { help = node.right; } else { help = node.left; } if (help != null && help.value < node.value) { valuehelper = node.value; node.value = help.value; help.value = valuehelper; } else { return; } node = help; } }
5
public void testPropertySetHour() { LocalTime test = new LocalTime(10, 20, 30, 40); LocalTime copy = test.hourOfDay().setCopy(12); check(test, 10, 20, 30, 40); check(copy, 12, 20, 30, 40); try { test.hourOfDay().setCopy(24); fail(); } catch (IllegalArgumentException ex) {} try { test.hourOfDay().setCopy(-1); fail(); } catch (IllegalArgumentException ex) {} }
2
public static int[] access(int[] a,int[] reg,int rw) { int[] r=new int[ARRAY_ROWS]; int[] b1=new int[WORD_SIZE]; //generate row selects (and-circuit) for(int row=0;row<ARRAY_ROWS;row++) { int mask=4; r[row]=Function.and(Function.C_MEMORY,(row&1)>0?a[0]:Function.not(Function.C_MEMORY,a[0]),(row&2)>0?a[1]:Function.not(Function.C_MEMORY,a[1])); for(int m=2;m<ARRAY_COLS;m++,mask<<=1) r[row]=Function.and(Function.C_MEMORY,r[row],(row&mask)>0?a[m]:Function.not(Function.C_MEMORY,a[m])); } //write into selected cells (reg=cell=(cell & !read | reg & read)) for(int row=0;row<ARRAY_ROWS;row++) { for(int i=0;i<8;i++) cellarray[row][i]=Function.xor(Function.C_MEMORY,Function.and(Function.C_MEMORY,r[row],Function.not(Function.C_MEMORY,rw),reg[i]), Function.and(Function.C_MEMORY,r[row],rw,cellarray[row][i]), Function.and(Function.C_MEMORY,Function.not(Function.C_MEMORY,r[row]), cellarray[row][i])); // for(int i=8;i<ARRAY_COLS;i++) // cellarray[row][i]=Function.or(Function.and(r[row],Function.not(rw),reg[i]), // Function.and(r[row],rw,cellarray[row][i]), // Function.and(Function.not(r[row]), cellarray[row][i])); } // System.out.println(); //combine row signals and cell bits (or-circuit) //load b1 for(int i=0;i<WORD_SIZE;i++) { b1[i]=Function.xor(Function.C_MEMORY,Function.and(Function.C_MEMORY,r[0],cellarray[0][i]),Function.and(Function.C_MEMORY,r[1],cellarray[1][i])); for(int j=2;j<ARRAY_ROWS;j++) b1[i]=Function.xor(Function.C_MEMORY,b1[i],Function.and(Function.C_MEMORY,r[j],cellarray[j][i])); } return b1; }
9
private static void optimizeMoves(List<DefinedMove> path) { DefinedMove prevMove = null; int count = 1; for (ListIterator<DefinedMove> it = path.listIterator(); it.hasNext(); ) { DefinedMove move = it.next(); /* * Check if some move is repeated 3 times */ if (move.equals(prevMove)) count++; else count = 1; if (count == 3) { // We remove current move it.remove(); // Then we remove the 2 previous one it.previous(); it.remove(); it.previous(); it.remove(); if (RubiksCube2D.DEBUG) System.out.println("AI : we should replace last three " + move + " with a " + Move.inverse(move.getMove()) + "@" + move.getFaceIndex()); // Finally we replace with the inverse move move = new DefinedMove(Move.inverse(move.getMove()), move.getFaceIndex()); it.add(move); // We reinit the previous correctly then we reset the iterator at the current position prevMove = it.previous(); it.next(); count = 1; } /* * Check if some move is followed by its opposite */ if (prevMove != null && move.equals(new DefinedMove(Move.inverse(prevMove.getMove()), prevMove.getFaceIndex()))) { it.remove(); it.previous(); it.remove(); if (RubiksCube2D.DEBUG) System.out.println("AI : we should remove last " + move + " and its previous inverse " + prevMove); } prevMove = move; } }
7
@Override public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) { if (args.length == 1) { List<String> matches = new ArrayList<String>(); for (String subcommand : subcommands) { if (StringUtil.startsWithIgnoreCase(subcommand, args[0])) { matches.add(subcommand); } } for (Effect effect : Effect.values()) { if (StringUtil.startsWithIgnoreCase(effect.name(), args[0])) { matches.add(effect.name()); } } if (!matches.isEmpty()) { return matches; } } return null; }
6
public void move(int offsetX, int offsetY) { CPRect srcRect; offsetX += movePrevX; offsetY += movePrevY; if (moveInitSelect == null) { srcRect = getSelectionAutoSelect(); if (!getSelection().isEmpty()) { moveInitSelect = getSelection(); } } else { srcRect = (CPRect) moveInitSelect.clone(); } curLayer.copyFrom(undoBuffer); if (!moveModeCopy) { curLayer.clear(srcRect, 0); } curLayer.pasteAlphaRect(undoBuffer, srcRect, srcRect.left + offsetX, srcRect.top + offsetY); undoArea = new CPRect(); if (!moveModeCopy) { undoArea.union(srcRect); } srcRect.translate(offsetX, offsetY); undoArea.union(srcRect); invalidateFusion(); if (moveInitSelect != null) { CPRect sel = (CPRect) moveInitSelect.clone(); sel.translate(offsetX, offsetY); setSelection(sel); } // this is a really bad idea :D movePrevX2 = offsetX; movePrevY2 = offsetY; }
5
protected double generateAmplitude(double time, double amplitude){ double amp = amplitude; if(time<adsr.getAttackTime()){ double deltaAmp=this.amplitude/(getSampleRate()*adsr.getAttackTime()); //the rate of growth of amplitude per sample return amplitude+deltaAmp; } else if(time <adsr.getAttackTime()+adsr.getDecayTime()){ double a=amplitude- adsr.getSustainAmplitude(); //when amplitude =.0001*A[max value of 1] 127*A=0; double k = Math.log(.001)/(adsr.getDecayTime()*getSampleRate()); if(DEBUG && time<.26) System.out.println(k+" "+a+" "+adsr.getDecayTime()+" "+Math.log(.001)); return amplitude+k*a; } else if(time<adsr.getAttackTime()+adsr.getDecayTime()+adsr.getSustainTime()){ return amplitude; } else{ //when amplitude =.0001*A[max value of 1] 127*A=0; double k = Math.log(.001)/(adsr.getReleaseTime()*getSampleRate()); return amplitude+k*amplitude; } }
5
public void run() { try { oos = new ObjectOutputStream(connection.getOutputStream()); ois = new ObjectInputStream(connection.getInputStream()); } catch (Exception e) { e.printStackTrace(); return; } try { BufferedInputStream bis = new BufferedInputStream(connection.getInputStream()); while (true) { // Process the command that was sent by the client. // First preference to requests from client ServerCommandInterface sci = null; if (exitThread == true) { cleanup(); return; } if (bis.available() > 0) { sci = (ServerCommandInterface)ois.readObject(); } else if (!commandsQueue.isEmpty()) { sci = (ServerCommandInterface)commandsQueue.remove(); } if (sci != null) { System.out.println( "Thread processing command: " + sci); sci.process(this); System.out.println( "Done processing command: " + sci ); } } } // EOFException is encountered when this thread was expecting a command from the // client and suddenly the stream got closed. In that case, it can be assumed that // the client got disconnected. catch (EOFException e) { cleanup(); return; } catch (SocketException e) { cleanup(); return; } catch (Exception e) { // Encountered an exception. Probably I should close the connection and // remove the client. cleanup(); return; } }
9
public boolean skipPast(String to) throws JSONException { boolean b; char c; int i; int j; int offset = 0; int length = to.length(); char[] circle = new char[length]; /* * First fill the circle buffer with as many characters as are in the * to string. If we reach an early end, bail. */ for (i = 0; i < length; i += 1) { c = next(); if (c == 0) { return false; } circle[i] = c; } /* We will loop, possibly for all of the remaining characters. */ for (;;) { j = offset; b = true; /* Compare the circle buffer with the to string. */ for (i = 0; i < length; i += 1) { if (circle[j] != to.charAt(i)) { b = false; break; } j += 1; if (j >= length) { j -= length; } } /* If we exit the loop with b intact, then victory is ours. */ if (b) { return true; } /* Get the next character. If there isn't one, then defeat is ours. */ c = next(); if (c == 0) { return false; } /* * Shove the character in the circle buffer and advance the * circle offset. The offset is mod n. */ circle[offset] = c; offset += 1; if (offset >= length) { offset -= length; } } }
9
public static void setSpeed(int s) { if (s > MAX_SPEED || s < 1) { Debug.printWarning("Trying to set speed greater than maximum (" + MAX_SPEED + ")! Setting to max instead..."); speed = MAX_SPEED; return; } speed = s; }
2