method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
9b55a9f3-17fe-4f4e-95c1-9d8f754900d1
5
private Matrix normal(Matrix mat) { Matrix globalMat = new Matrix(new double[mat.numRows()][mat.numColumns()]); for(int term = 0; term < mat.numColumns(); term++) { double norm = 0; for(int doc = 0; doc < mat.numRows(); doc++) { double tf = mat.m[doc][term]; if (tf > 0) { norm += tf * tf; } } norm = Math.sqrt(norm); for(int doc = 0; doc < mat.numRows(); doc++) { if (mat.m[doc][term] > 0) { globalMat.m[doc][term] = norm; } } } return globalMat; }
1021c252-381a-4bc8-bdc2-e719d111be22
3
public void setEqualizer(Equalizer eq) { if (eq==null) eq = Equalizer.PASS_THRU_EQ; equalizer.setFrom(eq); float[] factors = equalizer.getBandFactors(); if (filter1!=null) filter1.setEQ(factors); if (filter2!=null) filter2.setEQ(factors); }
ddd45d0e-8098-4288-86c3-a614faf236a2
9
@Override public Query rewrite(IndexReader reader) throws IOException { final Term[] terms = phraseQuery.getTerms(); final int[] positions = phraseQuery.getPositions(); boolean isOptimizable = phraseQuery.getSlop() == 0 && n >= 2 // non-overlap n-gram cannot be optimized && terms.length >= 3; // short ones can't be optimized if (isOptimizable) { for (int i = 1; i < positions.length; ++i) { if (positions[i] != positions[i-1] + 1) { isOptimizable = false; break; } } } if (isOptimizable == false) { return phraseQuery.rewrite(reader); } PhraseQuery.Builder builder = new PhraseQuery.Builder(); for (int i = 0; i < terms.length; ++i) { if (i % n == 0 || i == terms.length - 1) { builder.add(terms[i], i); } } return builder.build(); }
c11d656a-2dcd-4d04-bec0-45d999f1f671
8
private void fireBullets(List<BulletCommand> bulletCommands) { BulletPeer newBullet = null; for (BulletCommand bulletCmd : bulletCommands) { if (Double.isNaN(bulletCmd.getPower())) { println("SYSTEM: You cannot call fire(NaN)"); continue; } if (gunHeat > 0 || energy == 0) { return; } double firePower = min( energy, min(max(bulletCmd.getPower(), Rules.MIN_BULLET_POWER), Rules.MAX_BULLET_POWER)); updateEnergy(-firePower); gunHeat += Rules.getGunHeat(firePower); newBullet = new BulletPeer(this, battleRules, bulletCmd.getBulletId()); newBullet.setPower(firePower); if (!turnedRadarWithGun || !bulletCmd.isFireAssistValid() || statics.isAdvancedRobot()) { newBullet.setHeading(gunHeading); } else { newBullet.setHeading(bulletCmd.getFireAssistAngle()); } newBullet.setX(x); newBullet.setY(y); } // there is only last bullet in one turn if (newBullet != null) { // newBullet.update(robots, bullets); battle.addBullet(newBullet); } }
5da21e4a-2aa9-45c2-9ee4-567d7bf00732
5
@Override public List<FoodCombo> getCurrentMenuChoices() throws RuntimeException { List<FoodCombo> items = new ArrayList<FoodCombo>(); try { // Make sure you always open a connection before trying to // send commands to the database. db.openConnection(FoodOrderDAO.DRIVER, FoodOrderDAO.URL, FoodOrderDAO.USER, FoodOrderDAO.PWD); String sql = "select * from menu_item order by item_name"; List<Map> rawData = db.findRecords(sql, true); for (Map record : rawData) { FoodCombo item = new FoodCombo(); String id = (record.get("name").toString()); item.setName(id); String name = String.valueOf(record.get("description")); item.setDescription(name); Double price = Double.valueOf(record.get("price").toString()); item.setPrice(price); items.add(item); } return items; } catch (IllegalArgumentException ex) { throw new RuntimeException(ex.getMessage(), ex); } catch (ClassNotFoundException ex) { throw new RuntimeException(ex.getMessage(), ex); } catch (SQLException ex) { throw new RuntimeException(ex.getMessage(), ex); } catch (Exception ex) { throw new RuntimeException(ex.getMessage(), ex); } }
e0c2fcd8-6f23-41d1-bb36-cb6f07e4c6b4
4
public String selectFile(int mode) { String returnVal = null; int ret = 0; final JFileChooser fc = new JFileChooser(); JFrame frame = new JFrame("FileChooser"); //show open or save dialog fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); if(mode == MODE_OPEN) { ret = fc.showOpenDialog(frame.getJMenuBar()); } else if (mode == MODE_SAVE) { ret = fc.showSaveDialog(frame.getJMenuBar()); } if (ret == JFileChooser.CANCEL_OPTION) { returnVal = null; } else if(ret == JFileChooser.APPROVE_OPTION) { File file=fc.getSelectedFile(); returnVal=file.getPath(); } return returnVal; }
0a7f7054-c5d6-400b-8f96-54381cb87446
4
private void initComponents() { this.setLayout(new GridLayout(3,1)); WinchPanel = new JPanel(); WinchPanel.setLayout(new GridLayout(1,2)); WinchPanel.setBackground(Color.WHITE); DrumPanel = new JPanel(); DrumPanel.setLayout(new GridLayout(1,2)); DrumPanel.setBackground(Color.WHITE); ParachutePanel = new JPanel(); ParachutePanel.setLayout(new GridLayout(1,2)); ParachutePanel.setBackground(Color.WHITE); winchNameField = new JLabel("Name"); winchBrakePressureField = new JLabel("Brake"); winchOptDataField = new JLabel("Optional"); drumNameField = new JLabel("Name"); drumCoreDiameterField = new JLabel("Core Diameter"); drumCableLengthField = new JLabel("Cable Length"); drumKFactorField = new JLabel("K Factor"); drumNumLaunchesField = new JLabel("Launches"); paraNameField = new JLabel("Name"); paraIDField = new JLabel("ID"); paraLiftField = new JLabel("Lift"); paraDragField = new JLabel("Drag"); paraWeightField = new JLabel("Weight"); winchList = new javax.swing.JList(); JScrollPane winchScroller = new JScrollPane(); winchScroller.setBackground(Color.WHITE); WinchPanel.add(winchScroller); JPanel winchInfoPanel = new JPanel(); winchInfoPanel.setBackground(Color.WHITE); winchInfoPanel.setLayout(new BoxLayout(winchInfoPanel, BoxLayout.PAGE_AXIS)); winchInfoPanel.add(winchNameField); winchInfoPanel.add(winchBrakePressureField); winchInfoPanel.add(winchOptDataField); winchInfoPanel.add(new JButton("Add Winch")); winchInfoPanel.add(new JButton("Edit Winch")); WinchPanel.add(winchInfoPanel); for(Winch winch : currentWinches) { winchModel.addElement(winch); } winchList.setModel(winchModel); winchList.addMouseListener(new java.awt.event.MouseAdapter() { @Override public void mouseClicked(java.awt.event.MouseEvent evt) { if(winchList.getSelectedIndex() >= 0){ Winch curWinch = (Winch)winchList.getSelectedValue(); data.setCurrentWinch(curWinch); winchNameField.setText("Name: " + curWinch.getName()); winchBrakePressureField.setText("Brake Pressure: " + String.valueOf(curWinch.getBrakePressure())); winchOptDataField.setText("Optional Data: " + curWinch.getOptionalData()); updateDrumList(); updateParachuteList(); } } }); winchScroller.setViewportView(winchList); drumList = new javax.swing.JList(); JScrollPane drumScroller = new JScrollPane(); DrumPanel.add(drumScroller); JPanel drumInfoPanel = new JPanel(); drumInfoPanel.setLayout(new BoxLayout(drumInfoPanel, BoxLayout.PAGE_AXIS)); drumInfoPanel.add(drumNameField); drumInfoPanel.add(drumCoreDiameterField); drumInfoPanel.add(drumCableLengthField); drumInfoPanel.add(drumKFactorField); drumInfoPanel.add(drumNumLaunchesField); drumInfoPanel.add(new JButton("Add Drum")); drumInfoPanel.add(new JButton("Edit Drum")); DrumPanel.add(drumInfoPanel); drumList.setModel(drumModel); drumList.addMouseListener(new java.awt.event.MouseAdapter() { @Override public void mouseClicked(java.awt.event.MouseEvent evt) { if(drumList.getSelectedIndex() >= 0){ Drum curDrum = (Drum)drumList.getSelectedValue(); drumNameField.setText("Name: " + curDrum.getName()); drumCableLengthField.setText("Cable Length: " + String.valueOf(curDrum.getCableLength())); drumCoreDiameterField.setText("Core Diameter: " + String.valueOf(curDrum.getCoreDiameter())); drumKFactorField.setText("K Factor: " + String.valueOf(curDrum.getKFactor())); drumNumLaunchesField.setText("Number Launches: " + String.valueOf(curDrum.getNumLaunches())); } } }); drumScroller.setViewportView(drumList); paraList = new javax.swing.JList(); JScrollPane paraScroller = new JScrollPane(); ParachutePanel.add(paraScroller); JPanel paraInfoPanel = new JPanel(); paraInfoPanel.setLayout(new BoxLayout(paraInfoPanel, BoxLayout.PAGE_AXIS)); paraInfoPanel.add(paraNameField); paraInfoPanel.add(paraIDField); paraInfoPanel.add(paraDragField); paraInfoPanel.add(paraLiftField); paraInfoPanel.add(paraWeightField); paraInfoPanel.add(new JButton("Add Parachute")); paraInfoPanel.add(new JButton("Edit Parachute")); ParachutePanel.add(paraInfoPanel); paraList.setModel(paraModel); paraList.addMouseListener(new java.awt.event.MouseAdapter() { @Override public void mouseClicked(java.awt.event.MouseEvent evt) { if(paraList.getSelectedIndex() >= 0){ Parachute curPara = (Parachute)paraList.getSelectedValue(); paraNameField.setText("Name: " + curPara.getName()); paraIDField.setText("ID: " + String.valueOf(curPara.getId())); paraLiftField.setText("Lift: " + String.valueOf(curPara.getLift())); paraDragField.setText("Drag: " + String.valueOf(curPara.getDrag())); paraWeightField.setText("Weight: " + String.valueOf(curPara.getWeight())); } } }); paraScroller.setViewportView(paraList); add(WinchPanel); add(DrumPanel); add(ParachutePanel); }
00252fe8-54e3-4d84-85cd-60d6bf380139
6
private void buildItemData( VgerItemData theItem, Document output, Element element ) { Element itemNode; itemNode = output.createElement( "Item" ); if ( theItem.getBarcode() != null ) itemNode.appendChild( makeTextNode( "ItemNumber", theItem.getBarcode(), output ) ); if ( theItem.getLocation() != null ) itemNode.appendChild( makeTextNode( "Location", theItem.getLocation(), output ) ); if ( theItem.getCallNo() != null ) itemNode.appendChild( makeTextNode( "CallNumber", theItem.getCallNo(), output ) ); if ( theItem.getNote() != null ) itemNode.appendChild( makeTextNode( "ItemInfo2", theItem.getNote(), output ) ); if ( theItem.getItemEnum() != null ) itemNode.appendChild( makeTextNode( "ItemVolume", theItem.getItemEnum(), output ) ); if ( theItem.getCopy() != null ) itemNode.appendChild( makeTextNode( "ItemIssue", theItem.getCopy(), output ) ); element.appendChild( itemNode ); }
76ef3484-95fd-42ae-8183-ad7c3d95f054
7
public static float[] rref2(float[] matrix, int matrixSize){ int i = 0; int j = 0; for(;j < matrixSize; j++){ float lastValue = 0; int largestRow = i; for(int k = i; k < matrixSize; k++){ final int pos = getPosistion(k, j, matrixSize+1); if(Math.abs(matrix[pos]) > lastValue){ lastValue = matrix[pos]; largestRow = k; } } /** * If found largest value in a row, swamp the row */ if(largestRow != i){ matrix = swapRows(matrix, matrixSize +1, i, largestRow); } /** * Multiple row i by 1/mij */ matrix = multipleRow(matrix, matrixSize+1, i, 1 / matrix[getPosistion(i, j, matrixSize+1)]); /** * For each row r, where 1≤r≤n and r≠i, add -Mrj times row i it row r */ for(int r = 0; r < matrixSize; r++){ if(r != i){ final float mrj = -matrix[getPosistion(r, j, matrixSize+1)]; for(int l = 0; l < matrixSize+1; l++){ matrix[getPosistion(r, l, matrixSize+1)] += mrj * matrix[getPosistion(i, l, matrixSize+1)]; } } } i++; } return matrix; }
e4f13ecf-8577-4611-aac7-c00484a436f7
0
public ThreadPoolScheduler() { String threads = System.getProperty("junit.parallel.threads", "16"); int numThreads = Integer.parseInt(threads); executor = Executors.newFixedThreadPool(numThreads); }
8dd009f5-28d8-412b-a4ce-9e58f054f22a
4
public void setNeighbors(){ for(int i = 0; i < gameBoard.length; i++){ for(int j = 0; j < gameBoard[i].length; j++){ if(j - 1 >= 0){ gameBoard[i][j].addNeighbor(gameBoard[(i+1)%12][(j+3)%4]); gameBoard[i][j].addNeighbor(gameBoard[i][(j+3)%4]); gameBoard[i][j].addNeighbor(gameBoard[(i+11)%12][(j+3)%4]); } //* else { gameBoard[i][j].addNeighbor(null); gameBoard[i][j].addNeighbor(null); gameBoard[i][j].addNeighbor(null); } /* */ //middle gameBoard[i][j].addNeighbor(gameBoard[(i+1)%12][j]); gameBoard[i][j].addNeighbor(gameBoard[(i+11)%12][j]); if(j + 1 < 4){ gameBoard[i][j].addNeighbor(gameBoard[(i+1)%12][(j+1)%4]); gameBoard[i][j].addNeighbor(gameBoard[i][(j+1)%4]); gameBoard[i][j].addNeighbor(gameBoard[(i+11)%12][(j+1)%4]); } //* else { gameBoard[i][j].addNeighbor(null); gameBoard[i][j].addNeighbor(null); gameBoard[i][j].addNeighbor(null); } /* */ } } }
8dd210ad-997b-47f3-8b47-e4448a01a872
0
public void remindBuyerMarkReceived(Auction auction){ auction.remindBuyerMarkReceived(); }
a640ace8-52c8-4409-a188-1993ac1c2eca
9
public static void main(String[] args) throws InterruptedException { if(!(args.length == 2 || (args.length == 3 && args[0].matches("-speedup|-scaleup")))) { System.out.println("Usage: java BruteForceDES [-scaleup|-speedup] t s"); System.out.println(" t number of threads control"); System.out.println(" s key size in bits"); System.out.println(" -speedup measure speedup by running successively with 1..t threads"); System.out.println(" -scaleup measure scaleup by running successively with 1..t threads"); System.out.println(" and key space s..t*s"); return; } // get the number of threads to use int numThreads = Integer.parseInt(args[args.length - 2]); // Get the argument int keybits = Integer.parseInt(args[args.length - 1]); if(args.length == 3 && args[0].equals("-speedup")) { for(int i = 1; i <= numThreads; i++) { breakDes(keybits, i, false); } } else if (args.length == 3 && args[0].equals("-scaleup")) { long baseRange = (0xFFFFFFFFFFFFFFFFL >>> (64 - keybits)) + 1; for(int i = 1; i <= numThreads; i++) { long maxkey = baseRange * i; // Accurate up to 52 bits of key long key = (long) (Math.random() * maxkey); breakDes(key, maxkey - 1, i, false); } } else { breakDes(keybits, numThreads, true); } }
59f0d92d-6281-4d2e-aa5a-5c6fec340d95
0
@After public void tearDown() throws Exception { this.scheduler.shutdown(); }
8804e21c-5ee9-47c2-b675-25088bbc0f08
8
public void setEtat (int etat){ super.setEtat(etat); switch (etat) { case initiale: { initSources(); btnEnregistrerOuvrage.setEnabled(true); textFieldTitre.setEnabled(true); textFieldIsbn.setEnabled(true); textFieldDateEd.setEnabled(true); textFieldEditeur.setEnabled(true); btnAnnulerOuvrage.setEnabled(true); lblTitre.setEnabled(true); lblISBN.setEnabled(true); lblDateEdition.setEnabled(true); lblEditeur.setEnabled(true); btnAnnulerAuteur.setEnabled(false); btnNouvelAuteur.setEnabled(false); textFieldNom.setEnabled(false); textFieldPrenom.setEnabled(false); lblPrenom.setEnabled(false); lblNom.setEnabled(false); lblMotsclefs.setEnabled(false); btnTerminer.setEnabled(false); if (!modeleCible.isEmpty()) btnCS.setEnabled(false); btnSC.setEnabled(false); listSource.setEnabled(false); listCible.setEnabled(false); break; } case inter1: { btnEnregistrerOuvrage.setEnabled(false); textFieldTitre.setEnabled(false); textFieldIsbn.setEnabled(false); textFieldDateEd.setEnabled(false); textFieldEditeur.setEnabled(false); btnAnnulerOuvrage.setEnabled(false); lblTitre.setEnabled(false); lblISBN.setEnabled(false); lblDateEdition.setEnabled(false); lblEditeur.setEnabled(false); btnAnnulerAuteur.setEnabled(true); btnNouvelAuteur.setEnabled(true); textFieldNom.setEnabled(true); textFieldPrenom.setEnabled(true); lblPrenom.setEnabled(true); lblNom.setEnabled(true); if (!_auteurs.isEmpty()) { lblMotsclefs.setEnabled(true); btnTerminer.setEnabled(true); if (!modeleCible.isEmpty()) btnCS.setEnabled(true); btnSC.setEnabled(true); listSource.setEnabled(true); listCible.setEnabled(true); } break; } case inter2: { textFieldNom.setText(""); textFieldPrenom.setText(""); lblMotsclefs.setEnabled(true); btnTerminer.setEnabled(true); if (!modeleCible.isEmpty()) btnCS.setEnabled(true); btnSC.setEnabled(true); listSource.setEnabled(true); listCible.setEnabled(true); break; } case finale: { lblMotsclefs.setEnabled(false); btnTerminer.setEnabled(false); btnCS.setEnabled(false); btnSC.setEnabled(false); listSource.setEnabled(false); listCible.setEnabled(false); break; } } }
b66011ee-4e74-4a2d-adb0-d69bcc47b849
0
public String getCity() { return city; }
d4ed90e4-7046-4fb7-bc0a-0aa29218ffd1
7
public static void main(String[] args) throws Throwable{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); for (String line; (line = in.readLine())!=null; ) { if(line.equals("*"))break; char[] txt=line.toCharArray(); int q = Integer.parseInt(in.readLine()); for (int cq = 0; cq < q; cq++) { StringTokenizer st = new StringTokenizer(in.readLine()); int i1 = Integer.parseInt(st.nextToken()); int j1 = Integer.parseInt(st.nextToken()); int c = 0; boolean paila = false; for (int i = i1,j=j1; i < line.length() && j< txt.length &&!paila; i++,j++) { if(txt[i]==txt[j]) c++; else paila=true; } sb.append(c+"\n"); } } System.out.print(new String(sb)); }
d38a47dd-cab3-4786-869d-99ea219c400e
4
public static int createDisplayList(Model m) { int displayList = glGenLists(1); glNewList(displayList, GL_COMPILE); { glMaterialf(GL_FRONT, GL_SHININESS, 120); glColor3f(0.4f, 0.27f, 0.17f); glBegin(GL_TRIANGLES); for (Model.Face face : m.getFaces()) { if (face.hasNormals()) { Vector3f n1 = m.getNormals().get(face.getNormalIndices()[0] - 1); glNormal3f(n1.x, n1.y, n1.z); } Vector3f v1 = m.getVertices().get(face.getVertexIndices()[0] - 1); glVertex3f(v1.x, v1.y, v1.z); if (face.hasNormals()) { Vector3f n2 = m.getNormals().get(face.getNormalIndices()[1] - 1); glNormal3f(n2.x, n2.y, n2.z); } Vector3f v2 = m.getVertices().get(face.getVertexIndices()[1] - 1); glVertex3f(v2.x, v2.y, v2.z); if (face.hasNormals()) { Vector3f n3 = m.getNormals().get(face.getNormalIndices()[2] - 1); glNormal3f(n3.x, n3.y, n3.z); } Vector3f v3 = m.getVertices().get(face.getVertexIndices()[2] - 1); glVertex3f(v3.x, v3.y, v3.z); } glEnd(); } glEndList(); return displayList; }
24a2c865-5e5a-4963-8ac4-b093a7188386
3
public String next() { String url = null; Node parent = current.getParent(); if (parent != null) { int lenght = current.subNode.size(); Node next = null; for (int i = 0; i < lenght; i++) { if (current.getURL().equals(next = current.subNode.get(i))) { return next.getURL(); } } } else { } return url; }
c4c66dee-2067-443b-803c-a16d6b70b99e
0
public static void runEditorFrame(){ editorFrame = new EditorFrame(); editorFrame.setVisible(true); }
d2c56c98-b1d3-4364-badc-25ce545b69f6
3
private void VoltarMenuPrincipal_ButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_VoltarMenuPrincipal_ButtonActionPerformed if ("Visitante".equals(a.getTipoUtilizador())) { new Visitante(a); } if ("Gestor".equals(a.getTipoUtilizador())) { new Gestor(a); } if ("Juíz".equals(a.getTipoUtilizador())) { new Juiz(a); } this.dispose(); }//GEN-LAST:event_VoltarMenuPrincipal_ButtonActionPerformed
253d92e5-037b-4990-b842-c6ed8f248148
2
@Override public void run() { String msg = input.nextLine(); while (!msg.equals(ProtocolStrings.STOP)) { notifyListeners(msg); msg = input.nextLine(); } try { socket.close(); } catch (IOException ex) { Logger.getLogger(ChatClient.class.getName()).log(Level.SEVERE, null, ex); } }
9b45cf8b-3a22-40e6-ae7e-61e613179ab6
1
public void fixObjects() { baseGenome = bestVariation; bestVariation = null; for (LabelGene gene : baseGenome) { avoids = avoids.union(gene.getGeometry()); gene.render(); } baseGenome = new LabeledGenome<LabelGene>(avoids); }
0624171b-6f5b-4b3a-bd91-d2c77d122ce4
7
public ArrayList<Integer> findSubstring(String S, String[] L) { // Start typing your Java solution below // DO NOT write main() function int n = S.length(); int m = L.length; ArrayList<Integer> res = new ArrayList<Integer>(); if (n == 0 || m == 0) return res; int perLen = L[0].length(); int length = 0; length = perLen * m; if (length > n) return res; // Calculate the index dictionary for each word in L HashMap<String, Integer> dictSubStr = new HashMap<String, Integer>(); for (int i = 0; i < m; i++) { // Filter the same subString if (dictSubStr.containsKey(L[i])) { dictSubStr.put(L[i], dictSubStr.get(L[i]) + 1); continue; } dictSubStr.put(L[i], 1); } // 都不用DP...真伤心... for (int i = 0; i <= n - length; i++) { if (subFind(dictSubStr, m, perLen, S.substring(i, i + length), 0, L)) { // 只传部分字串能优化效率 res.add(i); } } return res; }
300f38f0-604b-458d-a19e-3c9439fdd47a
5
public MyGeneralTree<String> createGeneralTree(List<String> nodeDescriptors) { if(nodeDescriptors == null || nodeDescriptors.size() == 0) return null; NodeDescriptor rootDescriptor = null; List<NodeDescriptor> nodeDescriptorList = new ArrayList<>(); for(String nodeDescriptorString : nodeDescriptors) { //--- Split the current line into the three fields we need String[] tokens = nodeDescriptorString.split(":"); String id = tokens[0].trim(); String parentID = tokens[1].trim(); String data = tokens[2].trim(); NodeDescriptor nodeDescriptor = new NodeDescriptor(id, parentID, data); if(id.equals("0")) { System.out.println("We found a root"); rootDescriptor = nodeDescriptor; } else { nodeDescriptorList.add(nodeDescriptor); } } for(NodeDescriptor nodeDescriptor : nodeDescriptorList) System.out.println("List Node: " + nodeDescriptor.data); System.out.println("Root node: " + rootDescriptor.data); MyGeneralTreeNode rootNode = new MyGeneralTreeNode(rootDescriptor.data); rootNode = generateTree(rootNode, rootDescriptor, nodeDescriptorList); MyGeneralTree<String> returnTree = new MyGeneralTree(); returnTree.root = rootNode; return returnTree; }
d003339b-464a-423d-991d-0b9f10b21ede
6
@Override public void update() { if (rectangles.get(0) .contains(InputHandler.instance.getMouseLocation()) && !drawAll) { inactiveTimer.reset(); drawAll = true; } if ((InputHandler.instance.getMouseButton() == MouseEvent.BUTTON2) && (InputHandler.instance.getMouseButtonRotation() != 0)) { System.out.println(InputHandler.instance.getMouseButtonRotation()); // Prints twice. } if (inactiveTimer.getRemaining() == 0 && drawAll) { drawAll = false; } }
e2c0c76c-17af-493e-b001-2923df6a3271
2
public void printCycle(int cycleIndex, Main m){ int[] temp = cycles.get(cycleIndex); System.out.printf("\t Cycle %d:\n", cycleIndex); for(int i=0; i<temp.length; i++){ if(graphNodes.get(temp[i]).getType()== _REACTION_){ System.out.printf("\t"); m.getReactions().get( graphNodes.get(temp[i]).getID() ).printReaction(); } } System.out.printf("\n"); }
10333af4-d04d-4e3a-95db-92967695caf1
5
@Override public boolean state() { if (this.ticksHeld == 0) { return false; } if (this.ticksHeld == 1) { return true; } if (this.ticksHeld < this.initialDelay) { return false; } if (this.ticksHeld == this.initialDelay) { return true; } if ((this.ticksHeld - this.initialDelay) % this.repeatDelay == 0) { return true; } else { return false; } }
c5ce1cba-9fb9-4487-bf71-ae8e21d61cb1
8
public void testPingPong () throws IOException { fail = null; final Data dataTCP = new Data(); populateData(dataTCP, true); final Data dataUDP = new Data(); populateData(dataUDP, false); final Server server = new Server(16384, 8192); register(server.getKryo()); startEndPoint(server); server.bind(tcpPort, udpPort); server.addListener(new Listener() { public void connected (Connection connection) { connection.sendTCP(dataTCP); connection.sendUDP(dataUDP); // Note UDP ping pong stops if a UDP packet is lost. } public void received (Connection connection, Object object) { if (object instanceof Data) { Data data = (Data)object; if (data.isTCP) { if (!data.equals(dataTCP)) { fail = "TCP data is not equal on server."; throw new RuntimeException("Fail!"); } connection.sendTCP(data); } else { if (!data.equals(dataUDP)) { fail = "UDP data is not equal on server."; throw new RuntimeException("Fail!"); } connection.sendUDP(data); } } } }); // ---- final Client client = new Client(16384, 8192); register(client.getKryo()); startEndPoint(client); client.addListener(new Listener() { public void received (Connection connection, Object object) { if (object instanceof Data) { Data data = (Data)object; if (data.isTCP) { if (!data.equals(dataTCP)) { fail = "TCP data is not equal on client."; throw new RuntimeException("Fail!"); } connection.sendTCP(data); } else { if (!data.equals(dataUDP)) { fail = "UDP data is not equal on client."; throw new RuntimeException("Fail!"); } connection.sendUDP(data); } } } }); client.connect(5000, host, tcpPort, udpPort); waitForThreads(5000); }
27e6cb15-25f3-41a0-a548-72fa08e808ba
8
@Override public void update(GameContainer gc, StateBasedGame sb, int delta) throws SlickException { for (MenuButton button : buttons) { button.update(gc, sb, delta); } if (playButton.isMousePressed()) { if (Game.app.getFPS() >= 30) { if (firstTime) { fillAlpha = 175; firstTime = false; } sb.enterState(InGameState.ID, new FadeOutTransition(Color.black, TRANSITION_DELAY), new FadeInTransition(Color.black, TRANSITION_DELAY)); playButton.setImage(new Image("res/buttons/play.png")); } } if (settingsButton.isMousePressed()) { sb.enterState(SettingsState.ID, new FadeOutTransition(Color.black, TRANSITION_DELAY), new FadeInTransition(Color.black, TRANSITION_DELAY)); } if (helpButton.isMousePressed()) { sb.enterState(HelpState.ID, new FadeOutTransition(Color.black, TRANSITION_DELAY), new FadeInTransition(Color.black, TRANSITION_DELAY)); } if (exitButton.isMousePressed()) { System.exit(0); } Input input = gc.getInput(); if (Controller.isShortcutPressed("Menu", input)) { sb.enterState(InGameState.ID, new FadeOutTransition(Color.black, TRANSITION_DELAY), new FadeInTransition(Color.black, TRANSITION_DELAY)); } }
92288e3d-8d54-49e3-b105-bbadfb4c37fb
4
public void drawTextualMap(){ for(int i=0; i<grid.length; i++){ for(int j=0; j<grid[0].length; j++){ if(grid[i][j] instanceof Room){ if(((Room)grid[i][j]).getItems().size()>0) System.out.print(" I "); else System.out.print(" R "); }else{ System.out.print(" = "); } } System.out.println(); } System.out.println("rows = "+grid.length+" cols = "+grid[0].length); System.out.println("I = Room has Item, R = Room has no Item, '=' = Is a Hallway"); }
eb54c3fe-52f1-402c-a824-4a424cd6b308
6
public boolean sendData(Object data) { if (output == null || !clientSocket.isConnected()) { return false; } synchronized (this) { try { output.flush(); output.writeObject(data); output.flush(); output.reset(); if (data.getClass().equals(String.class)) { if (data.equals("goodbye")) { clientSocket.close(); if (serverSocket != null) { serverSocket.close(); } keepRunning = false; } } } catch (IOException e) { EIError.debugMsg("Network IO Error - Sending"); } return true; } }
57fd8e26-d79c-4412-bbf3-4ba5d90b222d
0
public int getLengthLifeInAquarium() { return lengthLifeInAquarium; }
841d3023-14b5-4a4a-a28a-78e3014db0c2
9
private void redoHelper(boolean fromNetwork) { //get the top of the action stack, handle it, and push it to the past actions stack for undo if(futureActions.empty()) { System.out.println("no actions to redo!"); return; } if(!fromNetwork) networking.sendAction(new BoardEltExchange(null, BoardActionType.REDO)); BoardElt be; BoardAction b = futureActions.pop(); switch(b.getType()) { case ELT_MOD: b.getTarget().redo(); b.getTarget().repaint(); pastActions.push(b); break; case CREATION: //redoing a creation means doing a creation be = b.getTarget(); if(be==null) return; boardElts.put(be.getUID(), be); if(be.getType()==BoardEltType.PATH) { paths.add((boardnodes.BoardPath)be); } else { panel.add(be); } pastActions.push(new CreationAction(be)); break; case DELETION: //redoing a deletion means doing a deletion be = b.getTarget(); if(be==null) return; boardElts.remove(be.getUID()); if(be.getType()==BoardEltType.PATH) { paths.remove(be); } else { panel.remove(be); } pastActions.push(new DeletionAction(be)); break; } panel.repaint(); }
985b814d-e583-44c4-aeeb-2fa6a27011af
5
@Override public void mousePressed(MouseEvent e) { final TCard source = (TCard) e.getSource(); if (e.getButton() == MouseEvent.BUTTON1) { tempCard = source; tempX = e.getX(); tempY = e.getY(); cardPosition = source.getCardPosition(); if (e.getClickCount() == 2) { if (source.isTapped()) { source.untap(); Game.client.send(new TapCard(source.getID(), false)); } else { source.tap(); Game.client.send(new TapCard(source.getID(), true)); } } } else { tempCard = null; } if (e.getButton() == MouseEvent.BUTTON3) { if (e.getClickCount() == 1) { JPopupMenu popupMenu = new JPopupMenu(); JMenuItem exile = new JMenuItem("exile"); exile.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Game.client.send(new MoveCard(Zone.TABLE, Zone.EXILED, -1, source.getID())); } }); JMenuItem moveToHand = new JMenuItem("return to hand"); moveToHand.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Game.client.send(new MoveCard( Zone.TABLE, Zone.HAND, -1, source.getID())); } }); JMenuItem moveToGraveyard = new JMenuItem("destroy"); moveToGraveyard.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Game.client.send(new MoveCard(Zone.TABLE, Zone.GRAVEYARD, -1, source.getID())); } }); JMenuItem moveToLibrary = new JMenuItem("put on top of library"); moveToLibrary.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Game.client.send(new MoveCard( Zone.TABLE, Zone.TOP_LIBRARY, -1, source.getID())); } }); popupMenu.add(moveToGraveyard); popupMenu.add(moveToHand); popupMenu.add(moveToLibrary); popupMenu.add(exile); popupMenu.show(source, e.getX(), e.getY()); } } }
c799ab43-f36f-44bb-86d3-549fc22735aa
9
public boolean searchMatrix(int[][] matrix, int target) { if (matrix.length == 1) { for (int i=0; i<matrix[0].length; i++) { if (matrix[0][i] == target) return true; } return false; } for (int i=1; i<matrix.length; i++) { if ( target > matrix[i-1][matrix[0].length-1] && target <= matrix[i][matrix[0].length-1] ) { int[] nums = new int[matrix[i].length]; for (int j=0; j<matrix[i].length; j++) { nums[j] = matrix[i][j]; } return binarySearch(nums, target); } else if (target <= matrix[i-1][matrix[0].length-1]) { int[] nums = new int[matrix[i].length]; for (int j=0; j<matrix[i-1].length; j++) { nums[j] = matrix[i-1][j]; } return binarySearch(nums, target); } } return false; }
d91a1377-804c-4bbf-a71c-8767e2b72916
0
public CATEGORY getCategory() { return this.category; }
a6889ee1-18b9-40d5-aabf-7f9593e2d82f
3
public static boolean isFree(int x, int y) { if (!inField(x, y) || !isFreeFromBricks(-1, x, y) || theField[x][y] == 2) { return false; } return true; }
7db5f4fb-db07-450c-9a8e-1aaf07ec3371
1
private void addRelativeMove(float x, float y) { Coordinate lastCoordinates; try { lastCoordinates = coordinates.getLast(); } catch (NoSuchElementException e) { lastCoordinates = new Coordinate(0, 0); } coordinates.add(new Coordinate(lastCoordinates.x+x, lastCoordinates.y+y)); }
db5835ea-366b-49ee-ad60-651d57c9ecc6
7
public static int LD (String s, String t) { int d[][]; // matrix int n; // length of s int m; // length of t int i; // iterates through s int j; // iterates through t char s_i; // ith character of s char t_j; // jth character of t int cost; // cost // Step 1 n = s.length (); m = t.length (); if (n == 0) { return m; } if (m == 0) { return n; } d = new int[n+1][m+1]; // Step 2 for (i = 0; i <= n; i++) { d[i][0] = i; } for (j = 0; j <= m; j++) { d[0][j] = j; } // Step 3 for (i = 1; i <= n; i++) { s_i = s.charAt (i - 1); // Step 4 for (j = 1; j <= m; j++) { t_j = t.charAt (j - 1); // Step 5 if (s_i == t_j) { cost = 0; } else { cost = 1; } // Step 6 d[i][j] = Minimum (d[i-1][j]+1, d[i][j-1]+1, d[i-1][j-1] + cost); } } // Step 7 return d[n][m]; }
76d1d0b6-aae3-4b4e-b999-686ee82521a7
0
protected final Logger getLogger() { return LoggerFactory.getLogger(this.getClass()); }
20aef808-3822-40ed-b71c-5f15b943b77f
7
public GeneralPath draw(Graphics2D g2, Rectangle2D dataArea, ValueAxis horizontalAxis, ValueAxis verticalAxis) { GeneralPath generalPath = generateClipPath( dataArea, horizontalAxis, verticalAxis ); if (this.fillPath || this.drawPath) { Composite saveComposite = g2.getComposite(); Paint savePaint = g2.getPaint(); Stroke saveStroke = g2.getStroke(); if (this.fillPaint != null) { g2.setPaint(this.fillPaint); } if (this.composite != null) { g2.setComposite(this.composite); } if (this.fillPath) { g2.fill(generalPath); } if (this.drawStroke != null) { g2.setStroke(this.drawStroke); } if (this.drawPath) { g2.draw(generalPath); } g2.setPaint(savePaint); g2.setComposite(saveComposite); g2.setStroke(saveStroke); } return generalPath; }
f9692426-2836-45a2-926c-2940576d8498
8
@Override public WindowsAttributes getWindowsAttributes(String path) throws PathNotFoundException, AccessDeniedException, UnsupportedFeatureException { if (hardlinks) { //Get hard link paths String[] hardlinks = getHardLinks(path); if (hardlinks.length > 0) path = hardlinks[0]; } if (windowsAttributes) { try { String[] lines = FileSystemUtils.readLines(attributeFs, getPermissionsPath(path)); if (lines.length > 3) { int permissions = Integer.valueOf(lines[3]); return new WindowsAttributes(permissions); } } catch (AccessDeniedException e) { e.printStackTrace(); } catch (NotAFileException e) { e.printStackTrace(); } catch (PathNotFoundException e) { if (!innerFs.pathExists(path)) throw e; } } return new WindowsAttributes(); }
b78547fc-b6ec-4cf7-a13b-16eb5d8072e0
0
public void setContent(String content) { mContent = content; }
845215c6-3670-44de-ab56-71499b16efad
3
@Override public void run() { init(); long start; long elapsed; long wait; // game loop while (running) { start = System.nanoTime(); update(); draw(); drawToScreen(); elapsed = System.nanoTime() - start; wait = targetTime - (elapsed / 1000000); if (wait < 0) { wait = 5; } try { Thread.sleep(wait); } catch (final Exception e) { e.printStackTrace(); } } }
16ff3e22-8a66-4236-ae2d-7d3207ab52e6
1
public Def availDef(final Def def) { final Def availDef = (Def) availDefs.get(def); if (SSAPRE.DEBUG) { System.out.println(" avail def for " + def + " is " + availDef); } return availDef; }
03903dc6-ac4e-4dd7-903d-65f2530a7263
5
public void writeKnownAttributes(GrowableConstantPool gcp, DataOutputStream output) throws IOException { if (bytecode != null) { output.writeShort(gcp.putUTF8("Code")); output.writeInt(bytecode.getSize()); bytecode.write(gcp, output); } if (exceptions != null) { int count = exceptions.length; output.writeShort(gcp.putUTF8("Exceptions")); output.writeInt(2 + count * 2); output.writeShort(count); for (int i = 0; i < count; i++) output.writeShort(gcp.putClassName(exceptions[i])); } if (syntheticFlag) { output.writeShort(gcp.putUTF8("Synthetic")); output.writeInt(0); } if (deprecatedFlag) { output.writeShort(gcp.putUTF8("Deprecated")); output.writeInt(0); } }
734c9480-8e91-45bd-b77f-caf80c14e2a6
0
public DocumentRepositoryListener[] getDocumentRepositoryListeners() { return (DocumentRepositoryListener[]) documentRepositoryListeners.toArray(); }
45f3e6d8-c268-4c61-9756-08d51352024c
8
public QryResult evaluateIndri(RetrievalModel r) throws IOException { // Initialization allocDaaTPtrs (r); QryResult result = new QryResult (); double queryVal = (double) 1 / (double)this.args.size(); // args / daat ? boolean looper = true; double tempScore = 0; DaaTPtr ptri; while (looper) { looper = false; double answer = 1; // the minDoc is initialized to max value int minDoc = Integer.MAX_VALUE; // Get the minimum docid from the inv lists. for (int i=0; i < this.daatPtrs.size(); i++) { ptri = this.daatPtrs.get(i); if (ptri.nextDoc == ptri.scoreList.scores.size()) continue; if (minDoc >= ptri.scoreList.getDocid (ptri.nextDoc)) { minDoc = ptri.scoreList.getDocid (ptri.nextDoc); looper = true; } } if (looper == false) break; for (int i=0; i < this.daatPtrs.size(); i++) { ptri = this.daatPtrs.get(i); if (ptri.nextDoc == ptri.scoreList.scores.size()) { tempScore = ((QryopSlScore) this.args.get(i)).getDefaultScore(r, minDoc); double poww = Math.pow(tempScore, queryVal); // INDRI answer = answer * poww; // INDRI continue; } if (minDoc != ptri.scoreList.getDocid (ptri.nextDoc)) { tempScore = ((QryopSlScore) this.args.get(i)).getDefaultScore(r, minDoc); double poww = Math.pow(tempScore, queryVal); // INDRI answer = answer * poww; // INDRI } else { tempScore = ptri.scoreList.getDocidScore(ptri.nextDoc); double poww = Math.pow(tempScore, queryVal); // INDRI answer = answer * poww; // INDRI ptri.nextDoc++; } } result.docScores.add (minDoc, answer); } freeDaaTPtrs (); return result; }
fee3f6f3-d8dd-47b6-92c0-72b27ba5040b
4
public String peekUnsearchList(){ final String sql = "SELECT min(sn), url FROM WAIT_SEARCH_URL_WIKI"; String sn = ""; String url = ""; Statement stmt; try { stmt = this.connection.createStatement(); ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { sn = rs.getString(1); url = rs.getString(2); if(sn == null || url == null){ log.info("WAIT_SEARCH_URL_WIKI 資料用檠"); return null; } } // Remove searched URI stmt.executeUpdate("Delete From WAIT_SEARCH_URL_WIKI Where Sn = " + sn); stmt.close(); } catch (SQLException ex) { log.error("SQLException: " + ex.getMessage()); } //GC sn = null; return url; }
4c886501-8694-48c0-b908-4cd282e84778
6
private void analyseLineFirstPass(String assemblyLine) throws AssemblerException { if (assemblyLine.equals(".data")){ if(dataDeclared) throw new AssemblerException(".data section already declared."); dataDeclared = true; atData = true; atText = false; } else if (assemblyLine.equals(".text")) { if(textDeclared) throw new AssemblerException(".text section already declared."); textDeclared = true; atData=false; atText=true; } else if (atData) analyseDataFirstPass(assemblyLine); else if (atText) analyseInstructionsFirstPass(assemblyLine); else throw new AssemblerException("No section header (\".data\" or \".text\")."); }
b302d127-2dfc-4629-a9fa-9b4f9617af0a
0
public Distance distanceTo(Point second) { double dx, dy, difference; dx = x - second.x; dy = y - second.y; difference = Math.sqrt(dx * dx + dy * dy); return new Distance(difference, unit); } } /* * Klasse voor een lijn. Bevat een twee punten en een meeteenheid * Deze klasse erft alles van vorm * Deze klasse bevat methode voor omtrek, die dezelfde methode in vorm klasse vervangt * Deze klasse bevat een toString methode die de default versie vervangt */ class Line extends Shape { double x2, y2; Line(Point p0, Point p1) { x = p0.x; y = p0.y; x2 = p1.x; y2 = p1.y; unit = p0.unit; } public Distance perimeter() { double dx, dy, length; dx = x - x2; dy = y - y2; length = Math.sqrt(dx * dx + dy * dy); return new Distance(length, unit); } public String toString() { return("Line[p0: (" + x + " " + unit + "; " + y + " " + unit + ");" + " P1: (" + x2 + " " + unit + "; " + y2 + " " + unit + ")]"); } } /* * Klasse voor een rechthoek. Bevat een middelpunt(x,y), lengte, breedte en meeteenheid * Deze klasse erft alles van vorm * Deze klasse bevat methode voor omtrek, die dezelfde methode in vorm klasse vervangt * Deze klasse bevat methode voor oppervlakte, die dezelfde methode in vorm klasse vervangt * Deze klasse bevat een toString methode die de default versie vervangt */ class Rectangle extends Shape { double xCenter, yCenter; Rectangle(Point p0, Distance a, Distance b) { super(a,b); xCenter = p0.x; yCenter = p0.y; } public Distance perimeter() { double result; result = x + x + y + y; return new Distance(result, unit); } public double area() { return x * y; } public String toString() { return("Rectangle[center: (" + xCenter + " " + unit + "; " + yCenter + " " + unit + "); width: " + x + " " + unit + "; length: " + y + " " + unit + "]"); } } /* * Klasse voor een cirkel. Bevat een middelpunt(x,y), radius en meeteenheid * Deze klasse erft alles van vorm * Deze klasse bevat methode voor omtrek, die dezelfde methode in vorm klasse vervangt * Deze klasse bevat methode voor oppervlakte, die dezelfde methode in vorm klasse vervangt * Deze klasse bevat een toString methode die de default versie vervangt */ class Circle extends Shape { double xCenter, yCenter, radius; Circle(Point p0, Distance a) { xCenter = p0.x; yCenter = p0.y; radius = a.number; unit = a.unit; } public Distance perimeter() { double result; result = 2 * Math.PI * radius; return new Distance(result, unit); } public double area() { return Math.PI * radius * radius; } public String toString() { return("Circle[radius:" + radius + " " + unit + "; center: (" + xCenter + " " + unit + "; " + yCenter + " " + unit + ")]"); }
3d049f61-8a9f-4e87-af07-013db2ab219e
6
public static void nextPermutation(int[] num) { int index = -1; int swap = -1; for (int i = num.length - 1; i > 0; i--) { if (num[i - 1] < num[i]) { index = i - 1; break;} } if (-1 != index) { for (int i = num.length - 1; i >= 0; i--) { if (num[i] > num[index]) {swap = i; break;} } int temp = num[swap]; num[swap] = num[index]; num[index] = temp; } for (int i = index + 1; i <= (index + 1 + num.length - 1) / 2; i++) { int temp = num[i]; num[i] = num[num.length - (i - index)]; num[num.length - (i - index)] = temp; } }
bae771bc-7608-4c56-9f4a-c7715ef15c9d
1
public static float sum(float[] arr){ float sum = 0; for (int i = 0 ; i < arr.length; i++){ sum += arr[i]; } return sum; }
87dfb3b7-0f50-4cdd-8c48-a8c9b003cf03
3
@Override public SampleableList sample() { SampleableListImpl output = new SampleableListImpl(); if (size() == 0) { return null; } for (int i = 0; i < size(); i = i + 2) { if (array[i] != null) { output.add(get(i).getReturnValue()); } else { break; } } return output; }
3a4a4a45-cce9-4ea5-a56a-2776386c9ec8
0
public Map<MetaEnum, Object> getMeta() { return this.getReferRequestWrapper().getMeta(); }
aea1298b-e8e7-4748-8047-a72572f04041
0
@Id @Column(name = "PCA_SECUEN") public Integer getPcaSecuen() { return pcaSecuen; }
8538cb51-e00a-4fe0-8dad-1861ccec4978
8
public static void main(String[] args) { int i = 0; outer: // Can�t have statements here for(; true ;) { // infinite loop inner: // Can�t have statements here for(; i < 10; i++) { System.out.println("i = " + i); if(i == 2) { System.out.println("continue"); continue; } if(i == 3) { System.out.println("break"); i++; // Otherwise i never // gets incremented. break; } if(i == 7) { System.out.println("continue outer"); i++; // Otherwise i never // gets incremented. continue outer; } if(i == 8) { System.out.println("break outer"); break outer; } for(int k = 0; k < 5; k++) { if(k == 3) { System.out.println("continue inner"); continue inner; } } } } }
e8741b97-1bed-4330-a3cd-891ddd62df1e
6
public ComputerControlPanel(final Computer computer) { super(new FlowLayout(FlowLayout.CENTER)); // Construct components final ExecutionSpeedSlider speedSlider = new ExecutionSpeedSlider(); final JButton step = new JButton("Step once"); JButton reset = new JButton("Reset computer"); JButton cancel = new JButton("Cancel execution"); JButton execute = new JButton("Execute program"); // Adds components to the panel add(new JLabel("Execution Speed:")); add(speedSlider); add(step); add(reset); add(cancel); add(execute); step.setEnabled(false); step.setToolTipText("Invokes the computer to execute the next instruction"); reset.setToolTipText("Resets the computer and reloads the program instructions into memory"); cancel.setToolTipText("Forces the computer to stop executing the running program"); execute.setToolTipText("Starts the computer executing the program instructions in memory"); // Add listeners speedSlider.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { if(!speedSlider.getValueIsAdjusting()) { int value = speedSlider.getValue(); step.setEnabled(value == 0); switch(value) { case 0 : computer.setExecutionSpeed(ExecutionSpeed.STEP); break; case 1 : computer.setExecutionSpeed(ExecutionSpeed.SLOW); break; case 2 : computer.setExecutionSpeed(ExecutionSpeed.MEDIUM); break; case 3 : computer.setExecutionSpeed(ExecutionSpeed.FAST); break; case 4 : computer.setExecutionSpeed(ExecutionSpeed.FULL); break; } } } }); reset.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { computer.reset(); } }); cancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { computer.forceStop(); } }); step.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { computer.step(); } }); execute.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { computer.execute(); } }); computer.addComputerListener(new ComputerAdapter() { public void breakPointHit(Computer computer, int breakpoint) { speedSlider.setValue(0); step.setEnabled(true); } }); }
390f6829-d5af-47ca-92ed-e03d909f7701
8
public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D)g; Graphics2D g3 = (Graphics2D)g; Graphics2D cookingArea = (Graphics2D)g; Graphics2D platingArea = (Graphics2D)g; //Clear the screen by painting a rectangle the size of the frame g2.setColor(getBackground()); g2.fillRect(0, 0, this.getWidth(), this.getHeight() ); g3.setColor(Color.BLACK); g3.drawString("CUSTOMER LINE", 20, 15); g3.drawString("COOK", 0, 150); g3.drawString("WAITER BREAK AREA", 240, 15); g3.drawString("TABLE 1", 50, 275); g3.drawString("TABLE 2", 200, 275); g3.drawString("TABLE 3", 350, 275); cookingArea.setColor(Color.PINK); cookingArea.fillRect(0, 60, 40, 80); platingArea.setColor(Color.CYAN); platingArea.fillRect(0, 150, 40, 80); int xPosUpdated=xPos; //Here is the table for (int i=1; i<=NTABLES; i++) //CREATING GUI TABLES { ImageIcon table = new ImageIcon("images/restaurantE_table.png"); Image image = table.getImage(); g.drawImage(image, xPosUpdated, yPos, null); // g2.setColor(Color.ORANGE); // g2.fillRect(xPosUpdated, yPos, Width, Height);//200 and 250 need to be table params xPosUpdated+=150; } for(Gui gui : guis) { if (gui.isPresent()) { gui.updatePosition(); } } for(Gui gui : guis) { if (gui.isPresent()) { gui.draw(g2); Graphics2D stringOrder = (Graphics2D)g; if (gui instanceof WaiterGui) { WaiterGui waiterGui = (WaiterGui) gui; waiterGui.drawOrder(stringOrder, waiterGui.text); } else if (gui instanceof CustomerGui) { CustomerGui customerGui = (CustomerGui) gui; customerGui.drawOrder(stringOrder, customerGui.text); } else if (gui instanceof CookGui) { CookGui cookGui = (CookGui) gui; cookGui.drawFirstPan(stringOrder, cookGui.firstPan); cookGui.drawSecondPan(stringOrder, cookGui.secondPan); cookGui.drawThirdPan(stringOrder, cookGui.thirdPan); cookGui.drawFirstPlate(stringOrder, cookGui.firstPlate); cookGui.drawSecondPlate(stringOrder, cookGui.secondPlate); cookGui.drawThirdPlate(stringOrder, cookGui.thirdPlate); } } } }
01cf3006-f7be-4e4f-8979-9d1760b26425
0
@Override public void operation() { getImplementor().operation(); }
0b181ec4-bdb1-4f07-9a1a-eb0cb1b62c5a
3
public double[] apply(double[] spectrumData) { if (spectrumData == null) { return null; } int specLen = spectrumData.length; int barkLen = getNumberOfBarkBands(); // initialize output vector double[] barkSpec = new double[barkLen]; // f ... frequency band, curFreq ... frequency represented by band f // f starts from 1 skipping DC component int b = 0; // b ... bark band index barkSpec[b] = 0; for (int f = 1; f < specLen / 2 + 1; f++) { double curFreq = f * this.binSizeHz; while (curFreq > BarkScale.BARK_LIMITS[b]) { b++; barkSpec[b] = 0; } barkSpec[b] += spectrumData[f]; } return barkSpec; }
ee88e9c5-b99d-44fb-a2d9-14b507ff894d
3
@Override public boolean isDone(Game game) { boolean ended = super.isFinished(game); if(ended) return true; if(game.getNumSprites(itype) - game.getNumDisabledSprites(itype) <= limit && canEnd) { countScore(game); return true; } return false; }
92bb34bc-eede-487a-b7f4-1257dfa475f5
1
public static final JsonElement toJson(Object object){ if(object instanceof String){ return parse((String)object); } return GSON.toJsonTree(object); }
7c827d51-9720-4b08-9f96-0035cd755181
9
protected void propagateClassifier() { switch (mappingChoice.getSelectedIndex()) { case RAYTRACE: // raytrace rendering. case VIEWSPACE: // viewspace. classificationChoice.setEnabled(true); if (classificationChoice.getSelectedIndex() == VJClassifiers.ISOSURFACE) classificationChoice.select(VJClassifiers.LEVOYNOINDEX); break; case ISOSURFACE: // isosurface. classificationChoice.setEnabled(false); classificationChoice.select(VJClassifiers.ISOSURFACE); break; } VJClassifier c = VJClassifiers.getClassifier(classificationChoice.getSelectedIndex()); if (c instanceof VJClassifier) { // Does classifier support indexing? if (indexChoice instanceof Choice) indexChoice.setEnabled(c.doesIndex()); if (c instanceof VJClassifierIsosurface) { thresholdField.setEnabled(true); widthField.setEnabled(false); ((VJClassifierIsosurface) c).setThreshold((float) getFloatField(thresholdField)); } else if (c instanceof VJClassifierValue) { thresholdField.setEnabled(true); widthField.setEnabled(false); ((VJClassifierValue) c).setThreshold((float) getFloatField(thresholdField)); } else if (c instanceof VJClassifierLevoy) { thresholdField.setEnabled(true); widthField.setEnabled(true); ((VJClassifierLevoy) c).setThreshold((float) getFloatField(thresholdField)); ((VJClassifierLevoy) c).setWidth((float) getFloatField(widthField)); } lutChoice.setEnabled(c.hasLUT()); classifierTextArea.setText(c.toLongString()); } classifier = null; v = null; }
fcdabcd1-2ba6-4f96-8ce1-c79edb3b6461
1
void parseDocument() throws java.lang.Exception { char c; parseProlog(); require('<'); parseElement(); try { parseMisc(); //skip all white, PIs, and comments c = readCh(); //if this doesn't throw an exception... error("unexpected characters after document end", c, null); } catch (EOFException e) { return; } }
523ea3e0-9f50-4e2f-8e06-841d9b3c9ba7
5
public void makeGlobalObject(int x, int y, int typeID, int orientation, int tileObjectType){ //Makes Global objects for (Player p : server.playerHandler.players){ if(p != null){ client person = (client)p; if((person.playerName != null || person.playerName != "null")){ if(person.distanceToPoint(x, y) <= 60){ person.createNewTileObject(x, y, typeID, orientation, tileObjectType); } } } } }
d304ae59-598e-48e1-a0ed-c52b4906324e
9
private void handleSubCommandPlayers(String[] args, Player executingPlayer) { if (args.length == 1) { GrubsMessager.sendMessage(executingPlayer, GrubsMessager.MessageLevel.ERROR, "Not enough arguments."); } if (GrubsLaserTag.getGameState() == GrubsLaserTag.GAME_STATES.ACCEPT_PLAYERS || GrubsLaserTag.getGameState() == GrubsLaserTag.GAME_STATES.ACCEPT_TIME_LIMIT) { ArrayList<Player> playersToAdd = new ArrayList<Player>(10); for (int i = 1, len = args.length; i < len; ++i) { List<Player> matches = Bukkit.matchPlayer(args[i]); if (matches.size() == 0) { GrubsMessager.sendMessage( executingPlayer, GrubsMessager.MessageLevel.ERROR, "No players matching '" + args[i] + "'." ); } else if (matches.size() == 1) { GrubsMessager.sendMessage( executingPlayer, GrubsMessager.MessageLevel.INFO, "Added player " + matches.get(0).getDisplayName() + "." ); playersToAdd.add(matches.get(0)); } else { String matchStr = ""; String separator = ""; for (int m = 0, matchNum = matches.size(); m < matchNum; ++m) { matchStr = separator + matches.get(m); if (m == 0) { separator = ", "; } } GrubsMessager.sendMessage( executingPlayer, GrubsMessager.MessageLevel.INQUIRY, "Matches for '" + args[i] + "': " + matchStr ); } } if (playersToAdd.size() > 0) { int added = GrubsLaserTag.setPlayers(playersToAdd.toArray(new Player[1])); GrubsMessager.sendMessage( executingPlayer, GrubsMessager.MessageLevel.INFO, "Added " + added + " players." ); GrubsMessager.sendMessage( executingPlayer, GrubsMessager.MessageLevel.INFO, "You can add more players or set time next." ); } } else { GrubsMessager.sendMessage( executingPlayer, GrubsMessager.MessageLevel.ERROR, "Current game not accepting players." ); } }
5fd1ada2-b134-4d57-8f10-6f43d7d30631
8
private void checkActivationName(String name, int token) { if (parser.insideFunction()) { boolean activation = false; if ("arguments".equals(name) || (parser.compilerEnv.activationNames != null && parser.compilerEnv.activationNames.containsKey(name))) { activation = true; } else if ("length".equals(name)) { if (token == Token.GETPROP && parser.compilerEnv.getLanguageVersion() == Context.VERSION_1_2) { // Use of "length" in 1.2 requires an activation object. activation = true; } } if (activation) { setRequiresActivation(); } } }
73f5d8dd-a6e4-46a1-b578-70f95e297530
8
public void move(ArrayList<Cell> moveableCells, Board board, Ball ball) { ArrayList<Cell> targetList = new ArrayList<Cell>(moveableCells); if(!hasBall) { //eDistanceBetween returns the straight line distance between 2 points. If the player is next to the ball, he attempts to steal //if he is not next to the ball, he checks to see if the target cell is closer to the ball and moves to it if he is, otherwise, he looks to the next target for (Cell target : moveableCells) { int targetIndex = board.calcIndex(target.getRow(), target.getCol()); if(ball.isNear(currentLocation)) { System.out.println("ball" + ball.getLocation()); System.out.println("player" + currentLocation); System.out.println(ball.isNear(currentLocation)); stealBall(ball); return; } else { if (board.eDistanceBetween(targetIndex, ball.getLocation()) < board.eDistanceBetween(currentLocation, ball.getLocation())) { setLocation(targetIndex); return; } } } } else if(hasBall) { int goalIndex = board.calcIndex(board.getRow(currentLocation), goalColumn); for (Cell target : moveableCells) { int targetIndex = board.calcIndex(target.getRow(), target.getCol()); if(Math.abs(goalColumn - board.getCol(currentLocation)) <= 1) { ball.setLocation(goalIndex); scores++; return; } else { if (board.eDistanceBetween(targetIndex, goalIndex) < board.eDistanceBetween(currentLocation, goalIndex)) { ball.setLocation(targetIndex); setLocation(targetIndex); return; } } } } }
8e5020be-1b22-4c67-9f21-ca7b21bc737d
6
static protected void UpdateLineColumn(char c) { column++; if (prevCharIsLF) { prevCharIsLF = false; line += (column = 1); } else if (prevCharIsCR) { prevCharIsCR = false; if (c == '\n') { prevCharIsLF = true; } else line += (column = 1); } switch (c) { case '\r' : prevCharIsCR = true; break; case '\n' : prevCharIsLF = true; break; case '\t' : column--; column += (tabSize - (column % tabSize)); break; default : break; } bufline[bufpos] = line; bufcolumn[bufpos] = column; }
2448f60c-0820-4ced-9409-c2b462300b93
4
@EventHandler public void onPlayerJoin(PlayerJoinEvent event) { final Player player = event.getPlayer(); if (plugin.getConfig().getBoolean("Optional.Login_Activation")) { plugin.getServer().getScheduler() .runTaskAsynchronously(plugin, new Runnable() { public void run() { if (plugin.checkAccount(player)) { if (!plugin.checkActivated(player)) { plugin.sendInfo(player, "Forum Account Found. Activating..."); if (plugin.activateUser(player)) plugin.activateCommands(player .getName()); } } } }); } }
94d86d87-a6a8-465a-b8a6-f3d21219dd44
1
public MemoryMapper(String outputdir,String filename){ int i; //memc=new byte[65536]; memnc=new int[65536]; for(i=0;i<65536;i++){ // memc[i]=0; memnc[i]=0; } dumpFile=new File(outputdir,filename+".mmap"); }
f0df25ac-b866-41c1-b6c9-8ebb6647b808
6
public boolean checkRessourceAvailability(int resType, String startDate, String endDate, int requestedQty) { //CONNECTION SKAL IKKE MED I PARAM, HENT FRA GETINSTANCE. SLET KALD HELE VEJEN GENNEM STRUKTUREN int bookedQty = 0; int totalStorageQty = 0; //startDate = "2014-01-13"; //endDate = "2014-01-17"; //ArrayList<Integer> orderIDList = new ArrayList<Integer>(); Er ikke brugt PT String SQLString1 = "SELECT sum(qty) FROM Orderdetails WHERE OrderID IN (" + " SELECT orderID FROM Orders WHERE (" + " (startDate>=? AND endDate<=?) or" + " (endDate>=? AND endDate>=?) OR" + " (startDate>=?) OR" + " (startDate<=? AND endDate>=? AND startDate<=? AND endDate>=? )" + " ) " + " AND confirmed=1)" + " AND RessourceTypeID = ?"; //SELECTER qty for en given RESOURCETYPEID i en GIVEN tidsperiode, to datoer, hvor order = confirmed PreparedStatement statement = null; try { statement = DBConnector.getInstance().getConnection().prepareStatement(SQLString1); statement.setString(1, startDate); statement.setString(2, endDate); statement.setString(3, startDate); statement.setString(4, endDate); statement.setString(5, endDate); statement.setString(6, startDate); statement.setString(7, startDate); statement.setString(8, endDate); statement.setString(9, endDate); statement.setInt(10, resType); ResultSet rs = statement.executeQuery(); if (rs.next()) { bookedQty += rs.getInt(1); System.out.println("Qty for restype(" + resType + ") is " + rs.getInt(1) + " between " + startDate + " and " + endDate); } } catch (Exception e) { System.out.println("Fail1 Checkavail " + e.toString()); } //Nu findes det totale ledige amount. ved at finde alle oprettede ressources, med det ønskede resTypeID //Ledig-QTY = total-QTY-used-QTY SQLString1 = "SELECT sum(qty) FROM Ressources WHERE ressourceTypeID=?"; try { statement = DBConnector.getInstance().getConnection().prepareStatement(SQLString1); statement.setInt(1, resType); ResultSet rs = statement.executeQuery(); while (rs.next()) { totalStorageQty += rs.getInt(1); } } catch (Exception e) { System.out.println("Fail2 " + e.toString()); } finally { try { } catch (Exception e) { System.out.println("Fail3 " + e.toString()); } } System.out.println("Qty for restype(" + resType + ") is " + totalStorageQty + " on all storages"); if (requestedQty <= (totalStorageQty - bookedQty)) { System.out.println("Der er nok"); return true; } else { System.out.println("Der er ikke nok"); return false; } }
a6984a23-51c8-4ba6-9c9a-0a1f91ed1a0f
4
public static void main(String[] args) { for( int i=0; i<POPULATION_SIZE; i++ ) population[i] = new Individual(); // for( int i=0; i<POPULATION_SIZE; i++ ) // System.out.println( "POPULATION[" + i + "]: " + population[i] ); for( int i=0; i<POPULATION_SIZE; i++ ) sumFitness += population[i].fitness; generation[ currentGeneration++ ] = sumFitness / POPULATION_SIZE; System.out.println( generation[ currentGeneration - 1 ] ); while( fittestSolution < .9 ) { fittestSolution = 0.0; generateNewPopulation( population ); if( currentGeneration % 100000 == 0 ) System.out.println( currentGeneration + "," + generation[ currentGeneration - 1 ] + "," + fittestSolution ); } }
531bc27e-08fa-49f2-9b9c-4d00452e9369
1
@Override public List<Funcao> Buscar(Funcao obj) { String Consulta = "select l from Funcao l"; if(obj != null){ Consulta = Consulta + " where l.nome like '%" + obj.getNome() + "%'"; } Query q = manager.createQuery(Consulta); return q.getResultList(); }
a6d73c75-430f-4a70-acb5-3e0a9a27043f
1
public void move() { if (nextGlied != null) { nextGlied.move(); } this.x += getDirection().getX() * width; this.y += getDirection().getY() * height; }
eb05484b-d2c2-46f3-9085-d9ca792f4809
8
private JSONArray buildJson() { JSONArray json = new JSONArray(); if (!initialized || entityIds.isEmpty()) { return json; } int i = 0, size = entityIds.size(); for (String entityID : entityIds) { try { JSONObject entityObj = new JSONObject(); JSONArray dispArr = new JSONArray(); entityObj.accumulate("entityID", entityID); if (idpMap.containsKey(entityID)) { Map<String, String> dispNames = idpMap.get(entityID); List<String> orderedLang = getOrderedLangList(dispNames); int orgIdx = 0, orgSize = orderedLang.size(); if (orderedLang.isEmpty()) { String name; try { name = entityID.substring(0, entityID.indexOf("/", 9)); } catch (Exception ex) { name = entityID; } JSONObject dispObj = new JSONObject(); dispObj.accumulate("value", name); dispObj.accumulate("lang", "en"); dispArr.put(dispObj); } else { for (String lang : orderedLang) { JSONObject dispObj = new JSONObject(); dispObj.accumulate("value", dispNames.get(lang)); dispObj.accumulate("lang", lang); dispArr.put(dispObj); } } } json.put(entityObj); entityObj.put("DisplayNames", dispArr); } catch (JSONException ex) { Logger.getLogger(MetaData.class.getName()).log(Level.SEVERE, null, ex); } } return json; }
390ae539-f469-4cc7-86b8-12b271096394
1
public static ItemFactory create(){ if(itemFactory == null){ itemFactory = new ItemFactory(); } return itemFactory; }
313b64dd-d66d-4f97-add2-d4c6f59a231c
0
@Override public void execute() { p.setBackground(Color.orange); }
d89ec535-90d7-46bd-9eac-be2049033b06
3
private double getGeneOverlap(LabelGene gene, GeometryFactory factory) { Geometry geometry = gene.getGeometry(); LinkedList<Geometry> overlappingObjects = new LinkedList<Geometry>(); overlappingObjects.add(avoids.intersection(geometry)); for (LabelGene otherGene : this) { if (otherGene != gene) { if (gene.getMaxExtend().intersects(otherGene.getMaxExtend())) { overlappingObjects.add(otherGene.getGeometry() .intersection(geometry)); } } } GeometryCollection overlap = new GeometryCollection(overlappingObjects.toArray(new Geometry[0]), factory); double overlapArea = overlap.getArea(); return overlapArea; }
2c7c5521-0c35-483e-91ec-457ed82ec5b4
5
public static float[][] getClusterDistance(int kc, float[][][] X, int min) { float tempX[][] = new float[kc][2]; float tempY[][] = new float[kc][2]; for (int i = 0; i < X.length; i++) { for (int j = 0; j < X.length; j++) { if ((int) X[i][0][0] >= min) { if (X[i][0][0] == X[j][0][0]) { tempX[(int) X[i][0][0] - min][0] = (int) X[i][0][0]; tempY[(int) X[i][0][0] - min][0] = (int) X[i][0][0]; tempX[(int) X[i][0][0] - min][1] = tempX[(int) X[i][0][0] - min][1] + getDataDistance(X[i][1], X[j][1]); tempY[(int) X[i][0][0] - min][1] = tempY[(int) X[i][0][0] - min][1] + 1; } } } } for (int i = 0; i < tempX.length; i++) { tempX[i][1] = tempX[i][1] / tempY[i][1]; } return tempX; }
e0d72b8a-fcea-49be-bb82-e324890d4540
2
public void setState(int state) { if (this.state != state) { this.state = state; stateTime = 0; if (state == STATE_DYING) { setVelocityX(0); setVelocityY(0); } } }
c275cf2d-65b3-4fee-a01b-071a5604e430
9
private static void splitWordsAndDefs(String[] str) { ArrayList<String> wordList = new ArrayList<String>(); ArrayList<String> defList = new ArrayList<String>(); for(String s : str) { String word = ""; String def = ""; char[] ch = s.toCharArray(); int section = 0; for(int i = 0; i < ch.length; i++) { if(section == 0) { if(ch[i] == ' ' && ch[i+1] == '-') { section = 1; } else { word += ch[i]; } } else { if(!((ch[i-1] == '-' && ch[i] == ' ') || (ch[i] == '-' && ch[i+1] == ' '))) { def += ch[i]; } } } wordList.add(word); defList.add(def); } words = wordList.toArray(new String[wordList.size()]); definitions = defList.toArray(new String[defList.size()]); }
a278ce40-04af-4be7-9131-f57ee92bdd20
2
@Override public int sizeOf( Class<?> v ) { return (v == null ? Compress.NULL_SIZE : Compress.sizeOfUnsignedNullable( v.getCanonicalName().length() ) + v.getCanonicalName().length() ); }
d5464ad8-2b1b-4dac-9dbb-4143e5820759
6
public void run(){ final double GAME_HERTZ = 40.0; //final double TARGET_FPS = 60.0; final double TIME_BETWEEN_UPDATES = 1000 / GAME_HERTZ; final int MAX_FRAMESKIP = 5; long lastTime = System.currentTimeMillis(); long currentTime = 0; long step = (long) TIME_BETWEEN_UPDATES; long sleepTime = 0; startInitialization(); isRunning = true; while (isRunning){ //currentTime = System.currentTimeMillis(); //step = currentTime - lastTime; //lastTime = currentTime; if (startPressed) { update(step); } //step += TIME_BETWEEN_UPDATES; if (!gameFinnished) { render(); } else { finishGame(); if (startPressed) { startInitialization(); } } //sleepTime = lastTime - System.currentTimeMillis(); if (sleepTime > 0) { try { Thread.sleep(sleepTime); } catch (InterruptedException e) { e.printStackTrace(); } } } }
91675060-3381-4ee1-ab80-f2b02e25cfc1
4
@Override public String buscarDocumentoPorEmpresa(String empresa) { ArrayList<Venta> geResult= new ArrayList<Venta>(); ArrayList<Venta> dbVentas = tablaVentas(); String result=""; try{ for (int i = 0; i < dbVentas.size() ; i++){ if(dbVentas.get(i).getEmpresa().equalsIgnoreCase(empresa)){ geResult.add(dbVentas.get(i)); //break; } } }catch (NullPointerException e) { result="No existe la venta con la empresa: "; } if (geResult.size()>0){ result=imprimir(geResult); } else { result="No se ha encontrado ningun registro"; } return result; }
3a4a8aea-6784-4709-8f86-3d96830c4452
8
@Override public void mousePressed(MouseEvent e) { cellWidth = view.getWidth() / view.getBoardSize(); cellHeight = view.getHeight() / view.getBoardSize(); pressedX = e.getX() / cellWidth; pressedY = e.getY() / cellHeight; if(pressedY == 0) { pressedY = 7; } else if(pressedY == 1) { pressedY = 6; } else if(pressedY == 2) { pressedY = 5; } else if(pressedY == 3) { pressedY = 4; } else if(pressedY == 4) { pressedY = 3; } else if(pressedY == 5) { pressedY = 2; } else if(pressedY == 6) { pressedY = 1; } else if(pressedY == 7) { pressedY = 0; } Piece piece = controller.getPieceFromBoard(pressedX, pressedY); Position piecePosition = new Position(pressedX, pressedY); view.getPossibleMovesToDraw(piece, piecePosition); view.repaint(); }
07dafe90-e9d3-4c19-b4f4-e3d91f9187c7
6
public MultiTermEnum(IndexReader topReader, IndexReader[] readers, int[] starts, Term t) throws IOException { this.topReader = topReader; queue = new SegmentMergeQueue(readers.length); matchingSegments = new SegmentMergeInfo[readers.length+1]; for (int i = 0; i < readers.length; i++) { IndexReader reader = readers[i]; TermEnum termEnum; if (t != null) { termEnum = reader.terms(t); } else termEnum = reader.terms(); SegmentMergeInfo smi = new SegmentMergeInfo(starts[i], termEnum, reader); smi.ord = i; if (t == null ? smi.next() : termEnum.term() != null) queue.add(smi); // initialize queue else smi.close(); } if (t != null && queue.size() > 0) { next(); } }
ec842e00-ca0c-4cc8-a708-1c11f157d4b6
8
private double leastSquaresNonMissing(Instances instances, int attIndex) { double numerator=0, denominator=0, w, t; double[] classMeans = new double[m_numOfClasses]; double[] classTotals = new double[m_numOfClasses]; for (int i=0; i<instances.numInstances(); i++) { LADInstance inst = (LADInstance) instances.instance(i); for (int j=0; j<m_numOfClasses; j++) { classMeans[j] += inst.zVector[j] * inst.wVector[j]; classTotals[j] += inst.wVector[j]; } } double numInstances = (double) instances.numInstances(); for (int j=0; j<m_numOfClasses; j++) { if (classTotals[j] != 0) classMeans[j] /= classTotals[j]; } for (int i=0; i<instances.numInstances(); i++) for (int j=0; j<m_numOfClasses; j++) { LADInstance inst = (LADInstance) instances.instance(i); if(!inst.isMissing(attIndex)) { w = inst.wVector[j]; t = inst.zVector[j] - classMeans[j]; numerator += w * (t * t); denominator += w; } } //System.out.println(numerator + " / " + denominator); return numerator > 0 ? numerator : 0;// / denominator; }
a8de045c-7002-4230-9c7d-f56c5a0610b9
2
public void render(){ for(int y = 0; y < height; y++){ for(int x = 0; x < width; x++){ Tile.getTileById(data.get((y * width) + x)).render(x * tileSize, y * tileSize); } } }
70143dab-7da5-47b1-86a5-d0549dd98401
3
@Override public Class getColumnClass(int column) { Class returnValue; if ((column >= 0) && (column < getColumnCount())) { if(getValueAt(0, column)==null) return String.class; returnValue = getValueAt(0, column).getClass(); } else { returnValue = Object.class; } return returnValue; }
323b2f76-9535-40a6-9645-93773a7af8a9
5
public static boolean hasMethod(final Class<?> clazz, final String name) { boolean found = Boolean.FALSE; if ((clazz != null) && (!StringUtils.isEmpty(name))) { int i = 0; final Method[] methods = clazz.getDeclaredMethods(); while ((i < methods.length) && (!found)) { found = methods[i].getName().equals(name); i++; } } return found; }
9bf78602-b28f-46f4-ae7a-151b6486f64f
6
public static void evaluateResult(TestVector v, Object result) { if (v.pass) { if (result instanceof String && v.expected.equals((String)result)) System.out.print("*PASS*: "); else System.out.print("*FAIL*: " ); System.out.println("input: [" + v.input + "] output: [" + v.expected + "] result: [" + result + "]"); } else { if (result==null|| !(result instanceof String)) System.out.print("*PASS*: "); else if (!v.expected.equals(result)) System.out.print("*PASS*: "); else System.out.print("*FAIL*: "); System.out.println("input: [" + v.input + "]"); } }
ed3b92ae-e9b5-4f8c-8688-c83d89419cb8
5
private void updateTabla(){ //** pido los datos a la tabla Object[][] vcta = this.getDatos(); //** se colocan los datos en la tabla DefaultTableModel datos = new DefaultTableModel(); tabla.setModel(datos); datos = new DefaultTableModel(vcta,colum_names_tabla); tabla.setModel(datos); //ajustamos tamaño de la celda Fecha Alta /*TableColumn columna = tabla.getColumn("Fecha Alta"); columna.setPreferredWidth(100); columna.setMinWidth(100); columna.setMaxWidth(100);*/ if (!field_codigo.getText().equals("")){ posicionarAyuda(field_codigo.getText()); } else{ if ((fila_ultimo_registro-1 >= 0)&&(fila_ultimo_registro-1 < tabla.getRowCount())){ tabla.setRowSelectionInterval(fila_ultimo_registro-1,fila_ultimo_registro-1); scrollCellToView(this.tabla,fila_ultimo_registro-1,fila_ultimo_registro-1); cargar_ValoresPorFila(fila_ultimo_registro-1); } else{ if ((fila_ultimo_registro+1 >= 0)&&(fila_ultimo_registro+1 <= tabla.getRowCount())){ tabla.setRowSelectionInterval(fila_ultimo_registro,fila_ultimo_registro); scrollCellToView(this.tabla,fila_ultimo_registro,fila_ultimo_registro); cargar_ValoresPorFila(fila_ultimo_registro); } } } }
0825782e-89a2-4902-b323-1efc01e61967
6
public static int getAbsoluteValue(int i, NumberSign sign) { if(i == 0 || i == -0) { return 0; } if(sign.equals(NumberSign.NEGATIVE)){ int r = (i < 0 ? i : -i); return r; } else if (sign.equals(NumberSign.POSITIVE)) { int r = (i < 0 ? -i : i); return r; } else { return 0; } }
de2e477c-e083-438b-8ef7-8a17099e5b9f
1
@Test public void testGetAvailableMoves() { System.out.println("getAvailableMoves"); Board board = new Board(8, 12); RuleManager instance = new RuleManager(); Set<Position> expResult = new HashSet<>(4); expResult.add(new Position(5, 2)); expResult.add(new Position(5, 4)); Set<Position> result = instance.getAvailableMoves(new Position(6, 3), board); assertEquals(expResult, result); expResult = new HashSet<>(4); expResult.add(new Position(5, 2)); result = instance.getAvailableMoves(new Position(6, 1), board); assertEquals(expResult, result); expResult = new HashSet<>(4); result = instance.getAvailableMoves(new Position(7, 2), board); assertEquals(expResult, result); board.changeFieldAt(new Position(7, 2), Board.EMPTY); board.changeFieldAt(new Position(7, 4), Board.EMPTY); board.changeFieldAt(new Position(6, 3), Board.BLACK_KING); expResult = new HashSet<>(4); expResult.add(new Position(5, 2)); expResult.add(new Position(5, 4)); expResult.add(new Position(7, 2)); expResult.add(new Position(7, 4)); result = instance.getAvailableMoves(new Position(6, 3), board); assertEquals(expResult, result); board = new Board(8, 12); try { board.movePiece(new Position(1, 2), new Position(5, 2)); board.movePiece(new Position(1, 4), new Position(5, 4)); } catch (IllegalPieceMovementException ex) { Logger.getLogger(RuleManagerTest.class.getName()).log(Level.SEVERE, null, ex); } expResult = new HashSet<>(4); expResult.add(new Position(4, 1)); expResult.add(new Position(4, 5)); result = instance.getAvailableMoves(new Position(6, 3), board); assertEquals(expResult, result); }
6cb50812-9f32-4d26-9d68-c8a5f9a78d10
9
public void calcBestPastrLocation() throws GameActionException { if (bestPastrLoc == null) { int MIDX = (rc.getMapWidth() / 2); int MIDY = (rc.getMapHeight() / 2); int[] info; switch (this.HQ_LOCATION) { case TOP: comms.sendSearchCoordinates(MIDX - CowGrowth.bigBoxSize, 0, rc.getMapWidth(), MIDY + CowGrowth.bigBoxSize); info = (new CowGrowth(this.rc, this).getBestLocation(0, 0, MIDX + CowGrowth.bigBoxSize, MIDY + CowGrowth.bigBoxSize)); comms.setP_PASTR_SCORE1(info[2]); comms.setP_PASTR_LOC1(new MapLocation(info[0], info[1])); break; case BOTTOM: comms.sendSearchCoordinates(MIDX - CowGrowth.bigBoxSize, MIDY - CowGrowth.bigBoxSize, rc.getMapWidth(), rc.getMapHeight()); info = (new CowGrowth(this.rc, this).getBestLocation(0, MIDY - CowGrowth.bigBoxSize, MIDX + CowGrowth.bigBoxSize, rc.getMapHeight())); comms.setP_PASTR_SCORE1(info[2]); comms.setP_PASTR_LOC1(new MapLocation(info[0], info[1])); break; case RIGHT: comms.sendSearchCoordinates(MIDX - CowGrowth.bigBoxSize, 0, rc.getMapWidth(), MIDY + CowGrowth.bigBoxSize); info = (new CowGrowth(this.rc, this).getBestLocation(MIDX - CowGrowth.bigBoxSize, MIDY - CowGrowth.bigBoxSize, rc.getMapWidth(), rc.getMapHeight())); comms.setP_PASTR_SCORE1(info[2]); comms.setP_PASTR_LOC1(new MapLocation(info[0], info[1])); break; case LEFT: comms.sendSearchCoordinates(0, 0, MIDX + CowGrowth.bigBoxSize, MIDY + CowGrowth.bigBoxSize); info = (new CowGrowth(this.rc, this).getBestLocation(0, MIDY - CowGrowth.bigBoxSize, MIDX + CowGrowth.bigBoxSize, rc.getMapHeight())); comms.setP_PASTR_SCORE1(info[2]); comms.setP_PASTR_LOC1(new MapLocation(info[0], info[1])); break; case TOP_RIGHT: comms.sendSearchCoordinates(0, 0, rc.getMapWidth(), MIDY + CowGrowth.bigBoxSize); info = (new CowGrowth(this.rc, this).getBestLocation(MIDX - CowGrowth.bigBoxSize, MIDY - CowGrowth.bigBoxSize, rc.getMapWidth(), rc.getMapHeight())); comms.setP_PASTR_SCORE1(info[2]); comms.setP_PASTR_LOC1(new MapLocation(info[0], info[1])); break; case TOP_LEFT: comms.sendSearchCoordinates(0, 0, rc.getMapWidth(), MIDY + CowGrowth.bigBoxSize); info = (new CowGrowth(this.rc, this).getBestLocation(0, MIDY - CowGrowth.bigBoxSize, MIDX - CowGrowth.bigBoxSize, rc.getMapHeight())); comms.setP_PASTR_SCORE1(info[2]); comms.setP_PASTR_LOC1(new MapLocation(info[0], info[1])); break; case BOTTOM_RIGHT: comms.sendSearchCoordinates(0, MIDY - CowGrowth.bigBoxSize, rc.getMapWidth(), rc.getMapHeight()); info = (new CowGrowth(this.rc, this).getBestLocation(MIDX - CowGrowth.bigBoxSize, 0, rc.getMapWidth(), MIDY + CowGrowth.bigBoxSize)); comms.setP_PASTR_SCORE1(info[2]); comms.setP_PASTR_LOC1(new MapLocation(info[0], info[1])); break; case BOTTOM_LEFT: comms.sendSearchCoordinates(0, 0, MIDX + CowGrowth.bigBoxSize, rc.getMapHeight()); info = (new CowGrowth(this.rc, this).getBestLocation(MIDX - CowGrowth.bigBoxSize, MIDY - CowGrowth.bigBoxSize, rc.getMapWidth(), rc.getMapHeight())); comms.setP_PASTR_SCORE1(info[2]); comms.setP_PASTR_LOC1(new MapLocation(info[0], info[1])); break; } bestPastrLoc = comms.wait_P_PASTR_LOC_2(); } }
d2ea3c35-e882-484b-8d78-b49f089f4da6
0
public ImportFileMenuItem(FileProtocol protocol) { setProtocol(protocol); addActionListener(this); }
f1727ef1-028e-489b-9269-6edb83cadea7
8
public boolean write( ) { boolean result = false; try { //Try to load the mysql Driver Class.forName("com.mysql.jdbc.Driver"); try { //Try to open a connection to the mysql server String url = settingsMap.get("URL"); String user = settingsMap.get("username"); String passwd = settingsMap.get("password"); Connection con = null; con = DriverManager.getConnection(url, user, passwd); Statement statement = con.createStatement(); //prepare a string representing inputDevice data String valueString = ""; String columnsString = ""; boolean first = true; for ( String key : targetDevice.getCurrentDataMap().keySet()) { if (first == false) { valueString = valueString+","; columnsString = columnsString+","; } columnsString = columnsString + key; String value = targetDevice.getCurrentDataMap().get(key)[0]; try{ //check if value is truly a number, else surround with quote marks for string Double.parseDouble(value); valueString = valueString+value; } catch(NumberFormatException e) { valueString=valueString+"'"+value+"'"; } first = false; } //finish preparing the entire sql query String table = settingsMap.get("table"); String sql = "INSERT INTO "+table+" ("+columnsString+") VALUES ("+valueString+")"; //DEBUG DEBUG DEBUG //System.out.println(sql); //execute query statement.execute(sql); result = true; try { //close all connections and statements if (statement != null) { statement.close(); } if (con != null) { con.close(); } } catch (Exception e) { System.out.println("WARNING: Failed to close MySQL connection!"); } } catch (SQLException e) { //catch connection exception // TODO Auto-generated catch block e.printStackTrace(); } } catch (ClassNotFoundException e) { //catch driver exception // TODO Auto-generated catch block e.printStackTrace(); } return result; }