method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
e8661589-b5a6-40d7-9d05-f236d363ecef
6
public void testApp() { // Create a map object TS3Map map = new TS3Map(); // Test the parseMapEntry() method Map.Entry<String, List<String>> entry = null; entry = map.parseMapEntry("name=value"); assertEquals(entry.getKey(), "name"); assertEquals(entry.getValue().size(), 1); assertTrue(entry.getValue().contains("value")); entry = map.parseMapEntry("entry=val1|entry=val2|entry=val3|entry=val4"); assertEquals(entry.getKey(), "entry"); assertEquals(entry.getValue().size(), 4); String[] values = {"val1", "val2", "val3", "val4"}; for(String value : values) assertTrue(entry.getValue().contains(value)); entry = map.parseMapEntry("-switch"); assertEquals(entry.getKey(), "switch"); assertNull(entry.getValue()); // Test the parseMap() method Map<String, List<String>> m = null; m = map.parseMap("name=value entry=val1|entry=val2|entry=val3 -switch"); assertEquals(m.size(), 3); assertTrue(m.containsKey("name")); assertTrue(m.containsKey("entry")); assertTrue(m.containsKey("switch")); assertNull(m.get("switch")); // Test the entryToString() method values = new String[] { "-switch", "name=value", "name=v1|name=v2" }; for(String value : values) { entry = map.parseMapEntry(value); assertEquals(map.entryToString(entry), value); } // Test the toString() method map = new TS3Map("name=value -switch"); // Since we're using a HashMap, the order may not be the same. boolean valid = false; if(map.toString().equals("name=value -switch")) valid = true; if(map.toString().equals("-switch name=value")) valid = true; assertTrue(valid); // Test the add methods map.clear(); map.add("name", "value"); assertEquals(map.toString(), "name=value"); map.clear(); map.add("entry", "v1"); map.add("entry", "v2"); map.add("entry", "v3"); assertEquals(map.toString(), "entry=v1|entry=v2|entry=v3"); map.clear(); map.add("client_id", 1); assertEquals(map.toString(), "client_id=1"); map.clear(); map.add("uids"); assertEquals(map.toString(), "-uids"); // Test the get methods map.clear(); // Ensure that the methods work properly when there is no such mapping assertFalse(map.contains("none")); assertNull(map.get("none")); assertNull(map.getList("none")); assertNull(map.getInteger("none")); assertNull(map.getIntegerList("none")); assertFalse(map.isList("none")); assertFalse(map.isInteger("none")); assertFalse(map.isSwitch("none")); // Test a single key with a single value map.add("entry", "value"); assertTrue(map.contains("entry")); assertEquals(map.get("entry"), "value"); assertNull(map.getInteger("entry")); assertFalse(map.isList("entry")); assertFalse(map.isInteger("entry")); assertFalse(map.isSwitch("entry")); // Test a single key with multiple values values = new String[] { "value1", "value2", "value3" }; for(String val : values) map.add("list", val); assertTrue(map.isList("list")); assertFalse(map.isInteger("list")); assertFalse(map.isSwitch("list")); assertNull(map.getInteger("list")); assertEquals(map.get("list"), "value1"); assertEquals(map.getList("list"), Arrays.asList(values)); // Test integers map.add("int", "123"); map.add("int2", 1234); assertTrue(map.isInteger("int")); assertTrue(map.isInteger("int2")); assertEquals(map.getInteger("int"), new Integer(123)); assertEquals(map.getInteger("int2"), new Integer(1234)); assertFalse(map.isList("int")); assertFalse(map.isSwitch("int")); // Test integer lists Integer[] intVals = new Integer[] { 1, 2, 3, 4 }; for(Integer val : intVals) map.add("intList", val); assertTrue(map.isList("intList")); assertEquals(map.getIntegerList("intList"), Arrays.asList(intVals)); // Test switches map.add("switch"); assertTrue(map.isSwitch("switch")); assertFalse(map.isList("switch")); assertFalse(map.isInteger("switch")); }
f590ce0f-9eea-46a8-8a92-a597e80231ab
5
private void setAutoSizeDimension() { if (!autoSize) { return; } if (image != null) { if (image.getHeight(null) == 0 || getHeight() == 0) { return; } if ((getWidth() / getHeight()) == (image.getWidth(null) / (image.getHeight(null)))) { return; } autoSizeDimension = adaptDimension(new Dimension(image.getWidth(null), image.getHeight(null)), this.getSize()); setSize(autoSizeDimension.width, autoSizeDimension.height); } }
46b69630-90c0-44b0-b9eb-552027abaee7
5
public boolean kopt(Kswap2 kswap, int[] rightCuts, int i, int length,int k,int index, boolean first){ if(k==0){ // System.out.println("doing k swap on: "+Arrays.toString(rightCuts)); return kswap.startFindBestSolution(rightCuts); } int limit=length; boolean improved=false; for(int iters=0; iters<limit; iters++){ rightCuts[index]=i; if(first){ //length -3 because are really choosing 2 vertices and the second vertice makes //it so that one extra place is forbidden //<-xOxn-> improved = kopt(kswap,rightCuts, Help.mod2(i+2, tour.length()), length-3,k-1, index+1, false) || improved; } else { //<-xOx(iters)Oxn-> improved = kopt(kswap,rightCuts, Help.mod2(i+2, tour.length()), length-iters-2,k-1, index+1, false) || improved; } i=Help.circleIncrement(i, tour.length()); } return improved; }
b2371be9-e4b8-43a6-8c39-5ae3899fac5d
8
public void moveLeft() { setDirection(-90); for (TetrisBug tb : blocks){ tb.setDirection(-90); } if (rotationPos==0){ if (canMove() && blocks.get(1).canMove()) { blocks.get(1).move(); move(); blocks.get(0).move(); blocks.get(2).move(); } } if (rotationPos == 1){ if (blocks.get(0).canMove() && blocks.get(1).canMove() && blocks.get(2).canMove()){ blocks.get(0).move(); move(); blocks.get(1).move(); blocks.get(2).move(); } } }
af205a05-6a44-495f-bd48-b5a3b96df549
5
private void rotateObject(PolygonObject toRotate, float x, float y) { int yRotate = 10; // maus koordinatensystem transformieren fuer rotation // sprich: verschiebe nach unten rechts x = x + 0.5f; y = y + 0.5f; if (toRotate != null) { // x-Rotation bewusst kleiner gehalten if (Math.abs(toRotate.getPrev_trans_y() - y) > 0) { if (y < toRotate.getPrev_trans_y()) { // links toRotate.setRotate_x(toRotate.getRotate_x() + 5); } else { // rechts toRotate.setRotate_x(toRotate.getRotate_x() - 5); } } if (Math.abs(toRotate.getPrev_trans_x() - x) > 0) { if (x < toRotate.getPrev_trans_x()) { // unten toRotate.setRotate_y(toRotate.getRotate_y() - yRotate); } else { // rechts toRotate.setRotate_y(toRotate.getRotate_y() + yRotate); } } toRotate.setPrev_trans_x(x); toRotate.setPrev_trans_y(y); } }
45a2687c-d4fe-4a07-9437-a7417504818f
9
private Data[] executeCommandsOnNodes(int commandType, final Command[] commands) throws InterruptedException{ final int maxCounterMsg; if(commandType == Command.INSERT_TABLE){ maxCounterMsg = 2; }else{ maxCounterMsg = numberOfNodes; } final CountDownLatch latch = new CountDownLatch(maxCounterMsg); final Data[] result = new Data[numberOfNodes]; for(int i=0; i!=numberOfNodes; ++i){ final int index = i; if(commands[index] == null) continue; Thread t = new Thread(new Runnable() { @Override public void run() { ++counterMsgSent; if(counterMsgSent == maxCounterMsg){ console.append("Command has been sent to " + counterMsgSent + " of " + maxCounterMsg + " nodes\n"); counterMsgSent = 0; } try { // output to the console if(!nodeNames[index].equals(myName)){ if(nodesSocket[index] != null){ // send to the node nodesOut[index].writeObject(Message.NODE); nodesOut[index].writeObject(commands[index]); // receive from the node result[index] = (Data)nodesIn[index].readObject(); } }else{ result[index] = dataBase.execute(commands[index]); } } catch (IOException e) { console.append("6. " + e.getMessage() + '\n'); nodesSocket[index] = null; nodesOut[index] = null; nodesIn[index] = null; } catch (ClassNotFoundException e) { console.append("7. "+ e.getMessage() + '\n'); }finally{ latch.countDown(); } ++counterMsgReceived; if(counterMsgReceived == maxCounterMsg){ console.append("Command has been recieved from " + counterMsgReceived + " of " + maxCounterMsg + " nodes\n"); counterMsgReceived = 0; } } }); t.start(); } latch.await(); return result; }
cd9e3624-068d-48f9-9b6a-972a0229b9e5
6
public SeasonCreatePanel() { // ------instantiations------- lblWelcomeText = new JLabel("Welcome to SurvivorPool!"); lblInfoText = new JLabel( "Fill out the fields below to create a new season."); lblWeeks = new JLabel("Weeks:"); lblContestants = new JLabel("Contestants:"); lblTribe1 = new JLabel("Tribe 1:"); lblTribe2 = new JLabel("Tribe 2:"); weekModel = new SpinnerNumberModel(3, 3, 12, 1); // default,low,min,step spnWeek = new JSpinner(weekModel); JFormattedTextField nonEditableWeek = ((JSpinner.DefaultEditor) spnWeek .getEditor()).getTextField(); nonEditableWeek.setEditable(false); contestantModel = new SpinnerNumberModel(6, 6, 15, 1);// default,low,min,step spnContestant = new JSpinner(contestantModel); JFormattedTextField nonEditableCont = ((JSpinner.DefaultEditor) spnContestant .getEditor()).getTextField(); nonEditableCont.setEditable(false); txtTribe1 = new JTextField(""); txtTribe2 = new JTextField(""); btnCreate = new JButton("Create Season"); fieldsPanel = new SeasonCreateFieldsPanel(lblWeeks, spnWeek, lblContestants, spnContestant, lblTribe1, txtTribe1, lblTribe2, txtTribe2, btnCreate); innerPanel = new JPanel(); // ------component settings------- this.setLayout(new BorderLayout()); this.setBorder(BorderFactory.createLineBorder(Color.black)); innerPanel.setLayout(new BorderLayout()); lblWelcomeText.setFont(new Font("sanserif", Font.BOLD, 30)); lblWelcomeText.setHorizontalAlignment(SwingConstants.CENTER); lblInfoText.setFont(new Font("sanserif", Font.ITALIC, 18)); lblInfoText.setHorizontalAlignment(SwingConstants.CENTER); // ------component assembly------ this.add(lblWelcomeText, BorderLayout.NORTH); this.add(innerPanel, BorderLayout.CENTER); innerPanel.add(lblInfoText, BorderLayout.NORTH); innerPanel.add(fieldsPanel, BorderLayout.CENTER); // ------component listeners------ spnWeek.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent ce) { JSpinner spn = (JSpinner) ce.getSource(); if (!programChange) // makes sure that the code did not change // the value changeSpinnerValue(spn); } }); spnContestant.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent ce) { JSpinner spn = (JSpinner) ce.getSource(); if (!programChange) changeSpinnerValue(spn); } }); btnCreate.addActionListener(new ActionListener() { // write the number of contestants and weeks to the file. @Override public void actionPerformed(ActionEvent ae) { try { if (checkValidTribeName(txtTribe1.getText())) { MainFrame.getRunningFrame().setStatusErrorMsg( "Invalid tribe name", txtTribe1); return; } else if (checkValidTribeName(txtTribe2.getText())) { MainFrame.getRunningFrame().setStatusErrorMsg( "Invalid tribe name", txtTribe2); return; } else if (txtTribe1.getText().equalsIgnoreCase(txtTribe2.getText())) { MainFrame.getRunningFrame().setStatusErrorMsg( "Invalid tribe names, cannot be the same", txtTribe1, txtTribe2); return; } GameData.initSeason(Integer.parseInt(spnContestant .getValue().toString())); GameData.getCurrentGame().setTribeNames( txtTribe1.getText(), txtTribe2.getText()); MainFrame.getRunningFrame().clearStatusError(); MainFrame.createSeason(); } catch (Exception i) { i.printStackTrace(); } } }); }
101544d4-a878-4a4b-868e-e2499b401a23
5
private void delete(int row) { if (!MyFactory.getResourceService().hasRight(MyFactory.getCurrentUser(), Resource.CONSUMPTION_W)) { return; } Consumption selectedRow = result == null ? null : result.get(row); if (selectedRow != null) { if (JOptionPane.showConfirmDialog(null, "确定要删除?") == JOptionPane.OK_OPTION) { if (MyFactory.getConsumptionService().delete(selectedRow.getId())) { JOptionPane.showMessageDialog(null, "删除成功!"); refreshData(); } } } }
1bc25873-bf20-4758-8479-5ae45918b216
1
public synchronized boolean remover(int i) { try { new AreaFormacaoDAO().remover(list.get(i)); list = new AreaFormacaoDAO().listar(""); preencherTabela(); } catch (Exception e) { return false; } return true; }
9fefb378-74f4-4dce-856a-b9689487e8d9
1
public void addTelefone(Telefone t){ if(!telefones.contains(t)){ this.telefones.add(t); } }
72468e51-76f8-4d1f-bddb-32bab28a41f5
1
private String executeCommand(String commandAsStr) { String response; try { response = client.sendRequestToServer(commandAsStr); } catch (HttpClientException e) { response = e.getMessage(); } return response; }
181087c4-4ace-45a9-9eac-7baef14693b4
7
public static final boolean addClass(final CMObjectType type, final CMObject O) { final Object set=getClassSet(type); if(set==null) return false; CMClass.lastUpdateTime=System.currentTimeMillis(); if(set instanceof List) { ((List)set).add(O); if(set instanceof XVector) ((XVector)set).sort(); } else if(set instanceof Hashtable) ((Hashtable)set).put(O.ID().trim().toUpperCase(), O); else if(set instanceof HashSet) ((HashSet)set).add(O); else return false; if(set==c().commands) reloadCommandWords(); if(set==c().libraries) CMLib.registerLibraries(c().libraries.elements()); return true; }
8ac47ed5-00a0-4786-95d1-470abea74252
3
public void remover(int codigo) throws ProdutoException { Produto prod = null; if(codigo < 0) throw new ProdutoException("CÛdigo inv·lido. Valor informado È menor que 0."); try { prod = buscarProduto(codigo); } catch (ProdutoException pe) { throw pe; } if(prod != null) produtos.remove(prod); }
d2c1f3c4-0734-4305-bec2-fbbe02e5b8a3
4
public boolean isFirstCharZero(String s) { if (s.length() < 1) { return false; } else { // 12:(00) is een uitzondering bij het detecteren van leading zero's if (s.length() > 1 && s.charAt(0) == '0' && s.charAt(1) != '0') { return true; } return false; } }
04d6d3b0-6f97-4f76-bee2-4b2609bce0da
5
private String adapter(String key) { String aRetourner=""; for(int i=0;i<key.length();i++) { if(key.charAt(i)>=65 && key.charAt(i)<=90) { aRetourner+=key.charAt(i); } if(key.charAt(i)>=97 && key.charAt(i)<=122) { aRetourner+=(char)(key.charAt(i)-32); } } return aRetourner; }
07eb3c9f-da07-4a9d-b4f0-9ebf83eb5389
8
public void right() { if (mState != jumping && mState != beginJump && mState != ducking && mState != hardLanding) { facing = right; mState = running; if (heroxSpeed < 0) heroxSpeed = .5f; else if (heroxSpeed < 4) heroxSpeed += .5f; } else if (mState == hardLanding) heroxSpeed *= .9; else { facing = right; if (heroxSpeed < 4) heroxSpeed += .25f; } }
9bbfebe9-4444-43f1-98f7-577e5e6f4cdb
2
private boolean checkFront(int x, int y, int z){ int dx = x + 1; if(dx > CHUNK_WIDTH - 1){ return false; }else if(chunk[dx][y][z] != 0){ return true; }else{ return false; } }
fd2450f0-0752-445d-8766-d88c53259a14
2
@Override public void removeAttribute(String key) { if (attributes != null) { if (key == null) { key = ""; } this.attributes.remove(key); this.isReadOnly.remove(key); } }
8598b0c9-5fc1-4dd0-a7ab-54b7344a7980
1
public double AverageScore() { double sum = 0; for (QuizResult qr: quizResults) { sum += qr.PercentScore(); } double avg = sum / quizResults.size(); return avg; }
8b9a0ed1-5a25-47c9-aaa2-c7cfc5681e5b
6
private void outputExcel(int orderChoice){ FileOutput fout = new FileOutput(this.outputFilename); fout.println(title[0]); fout.println((this.nItems)); fout.println(this.nPersons); for(int i=0; i<this.nItems; i++){ fout.printtab(this.itemNames[i]); } fout.println(); if(orderChoice==0){ for(int i=0; i<this.nItems; i++){ for(int j=0; j<this.nPersons; j++){ fout.printtab(Fmath.truncate(this.scores0[i][j], this.trunc)); } fout.println(); } } else{ for(int j=0; j<this.nPersons; j++){ for(int i=0; i<this.nItems; i++){ fout.printtab(Fmath.truncate(this.scores1[j][i], this.trunc)); } fout.println(); } } fout.close(); }
f6244dee-5c2c-4faa-9cf7-9b65c44fa3a1
1
public void calcBonusUnite() { // Calcul des gains d'unités si pouvoir spécial int bonusUnite = this.bonusUnite() + (hasPower() ? this.pouvoir.bonusUnite() : 0); bonusUnite = Math.min(this.nbUniteMax - this.nbUnite, bonusUnite); this.nbUnite += bonusUnite; this.nbUniteEnMain += bonusUnite; }
1cb57911-39a1-4693-81fc-379f6edcc53d
1
* * @return <tt>true</tt> iff the query is true in the knowledge base * * @throws IOException if a data communication error occurs * @throws CycApiException if the api request results in a cyc server error */ public boolean isQueryTrue_Cached(CycList query, CycObject mt) throws IOException, CycApiException { Boolean isQueryTrue = askCache.get(query); if (isQueryTrue != null) { return isQueryTrue.booleanValue(); } final boolean answer = isQueryTrue(query, makeELMt(mt)); askCache.put(query, answer); return answer; }
6e754b7d-bdd0-40c0-9b37-bba260f8dee6
5
public void setShutdownmenuButtonPosition(Position position) { if (position == null) { this.buttonShutdownmenu_Position = UIPositionInits.SHDMENU_BTN.getPosition(); setShutdownframeBorderlayout(false); } else { if (!position.equals(Position.LEFT) && !position.equals(Position.RIGHT) && !position.equals(Position.TOP) && !position.equals(Position.BOTTOM)) { IllegalArgumentException iae = new IllegalArgumentException( "The position not valid! Valid positions: left, right, top, bottom."); Main.handleUnhandableProblem(iae); } setShutdownframeBorderlayout(true); this.buttonShutdownmenu_Position = position; } somethingChanged(); }
a9aee2bd-6001-457c-9866-7ce13bb4fa08
8
private void FindNodes() { if (current.loc.x-1>=0&&unit.PathCheck(current.loc.x-1, current.loc.y)) { AddNode(current.loc.x-1,current.loc.y); } if (current.loc.y-1>=0&&unit.PathCheck(current.loc.x, current.loc.y-1)) { AddNode(current.loc.x,current.loc.y-1); } if (current.loc.x+1<Game.map.width&&unit.PathCheck(current.loc.x+1, current.loc.y)) { AddNode(current.loc.x+1,current.loc.y); } if (current.loc.y+1<Game.map.height) { if (unit.PathCheck(current.loc.x, current.loc.y+1)) { AddNode(current.loc.x,current.loc.y+1); } } }
d668a112-cb43-485a-b6bd-b78646280aed
0
private boolean areTriesLeft() { return gpm.getMaxTries() >= grid.getIntellingentMovementHistory() .size(); }
ced76869-b5ae-4371-946c-6391c6586cda
3
private void btnUploadSkinActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnUploadSkinActionPerformed if (fcSkin.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { File skinFile = fcSkin.getSelectedFile(); if (skinFile.exists() && skinFile.canRead()) { UploadSkinWorker usw = new UploadSkinWorker(this, skinFile, this.loggedUsername, this.session); usw.execute(); btnRemoveSkin.setEnabled(false); btnUploadSkin.setEnabled(false); btnUploadSkin.setText("Uploading..."); } } }//GEN-LAST:event_btnUploadSkinActionPerformed
1adf4cab-e298-42dc-b82d-e53e917e2531
9
public void generatePath(Vector2 bestStartPoint) { Segment2D prev = null; if (layer.skirt != null) { Polygon poly = layer.skirt.getLargestPolygon(); if (poly != null) { prev = poly.closestTo(bestStartPoint); layer.pathStart = prev; prev = poly.cutPoly(prev); } } for (int i = 0; i < layer.outlinePart.length; i++) { // Find the largest polygon. So we start with the biggest outline first. Polygon nextPoly = layer.outlinePart[i].getLargestPolygon(); if (nextPoly == null) return; Vector<Polygon> polys = layer.outlinePart[i].getPolygonListClone(); polys.remove(nextPoly); polys.add(0, nextPoly); while (polys.size() > 0) { nextPoly = polys.get(0); if (prev != null) { for (int n = 0; n < polys.size(); n++) { if (polys.get(n).getAABB().getAABBDist(prev) < nextPoly.getAABB().getAABBDist(prev)) nextPoly = polys.get(n); } } polys.remove(nextPoly); if (prev == null) { Segment2D startSegment = nextPoly.closestTo(bestStartPoint); layer.pathStart = startSegment; prev = nextPoly.cutPoly(startSegment); } else { Segment2D startSegment = nextPoly.closestTo(prev.end); Segment2D newPrev = nextPoly.cutPoly(startSegment); new Segment2D(Segment2D.TYPE_MOVE, prev, startSegment); prev = newPrev; } } } }
27179795-e218-4099-93f8-efa5e831f0d2
0
public SpecifiedActionListener(GUI gui, String text, boolean leaveZero) { this.gui = gui; this.text = text; this.leaveZero = leaveZero; }
5b5ed771-5a76-4bd3-a2a2-7a0fa2bb0549
3
@Action(name = "hcomponent.handler.onclick.invoke", args = { "undefined" }) public void onClickInvoke(Updates updates, String[] args, String param) { HComponent<?> html = (HComponent<?>) Session.getCurrent().get( "_hcomponent.object." + param); if (html.getOnClickListener() != null) Session.getCurrent() .gethActionManager() .invokeHAction(html.getOnClickListener(), updates, args, param); }
0e2c81fd-383e-40b4-83e1-e1b35fb4b088
8
public void testBinaryCycAccess16() { System.out.println("\n**** testBinaryCycAccess 16 ****"); CycAccess cycAccess = null; try { try { if (connectionMode == LOCAL_CYC_CONNECTION) { cycAccess = new CycAccess(testHostName, testBasePort); } else if (connectionMode == SOAP_CYC_CONNECTION) { cycAccess = new CycAccess(endpointURL, testHostName, testBasePort); } else { fail("Invalid connection mode " + connectionMode); } } catch (Throwable e) { fail(e.toString()); } //cycAccess.traceOnDetailed(); try { if (!(cycAccess.isOpenCyc())) { List genls = null; CycConstant carAccident = null; carAccident = cycAccess.getKnownConstantByGuid(CAR_ACCIDENT_GUID_STRING); genls = cycAccess.getGenls(carAccident); assertNotNull(genls); assertTrue(genls instanceof CycList); Iterator iter = genls.iterator(); while (iter.hasNext()) { Object obj = iter.next(); assertTrue(obj instanceof CycFort); } List coExtensionals = null; coExtensionals = cycAccess.getCoExtensionals(carAccident); assertNotNull(coExtensionals); assertTrue(coExtensionals instanceof CycList); iter = coExtensionals.iterator(); while (iter.hasNext()) { Object obj = iter.next(); assertTrue(obj instanceof CycFort); } } } catch (Throwable e) { e.printStackTrace(); fail(e.toString()); } } finally { if (cycAccess != null) { cycAccess.close(); cycAccess = null; } } System.out.println("**** testBinaryCycAccess 16 OK ****"); }
7875fdad-f0e0-42c3-ae0b-b487a5fff840
2
private void copyBack(int[][] origin, int iStart, int iEnd, int jStart, int jEnd, int[][] subMatrix) { for (int i = iStart; i < iEnd; ++i) for (int j = jStart; j < jEnd; ++j) origin[i][j] = subMatrix[i-iStart][j-jStart]; }
88a85e40-ba49-41ae-a0e7-b2404d6236af
4
@Test public void test_mult_skalar() { int a = 2; int b = 3; int skalar = -4; Matrix m1 = new MatrixArrayList(a, b); Matrix m2 = new MatrixArrayList(a, b); for (int i = 1; i <= a; i++) { for (int j = 1; j <= b; j++) m1.insert(i, j, (double) (2 * i - j)); } for (int i = 1; i <= a; i++) { for (int j = 1; j <= b; j++) m2.insert(i, j, (double) ((2 * i - j) * skalar)); } assertEquals(m1.mul(skalar), m2); }
6f43ca06-c7c8-4f65-b010-ec6c432a4ca7
5
private void createHdr() { hdrData = new float[width * height * 3]; double[] relevances = new double[width * height]; int color; double red, green, blue; boolean isPixelSet; for (int i = 0; i < width * height; i++) { isPixelSet = false; for (MyImage img : images) { double relevance = 1 - ((Math.abs(img.getLuminance(i) - 127) + 0.5) / 255); if (relevance > 0.05) { isPixelSet = true; color = img.getBufferedImage().getRGB(i % width, i / width); red = (color & 0x00ff0000) >> 16; green = (color & 0x0000ff00) >> 8; blue = color & 0x000000ff; hdrData[i * 3 + 0] += red * relevance / img.getExposure(); hdrData[i * 3 + 1] += green * relevance / img.getExposure(); hdrData[i * 3 + 2] += blue * relevance / img.getExposure(); relevances[i] += relevance; } } if (!isPixelSet) { MyImage img = images.get(images.size() / 2); color = img.getBufferedImage().getRGB(i % width, i / width); red = (color & 0x00ff0000) >> 16; green = (color & 0x0000ff00) >> 8; blue = color & 0x000000ff; hdrData[i * 3 + 0] += red / img.getExposure(); hdrData[i * 3 + 1] += green / img.getExposure(); hdrData[i * 3 + 2] += blue / img.getExposure(); relevances[i] = 1; } } for (int i = 0; i < width * height; i++) { hdrData[i * 3 + 0] /= relevances[i]; hdrData[i * 3 + 1] /= relevances[i]; hdrData[i * 3 + 2] /= relevances[i]; } System.out.println("done"); }
bd8cb92f-23ac-4a50-a783-e7598018567b
7
public int getDirectionFacing(){ if( controller.getY() == 1 && !isOnGround ){ facingDown = true; } else if( controller.getY() == 1 ) { this.currentPosition.y--; this.oldPosition.y--; } else { facingDown = false; } if (controller.getX() < 0 && directionFacing != -1){ directionFacing = -1; return -1; } else if (controller.getX() > 0 && directionFacing != 1){ directionFacing = 1; return 1; } return directionFacing; }
a1f364bc-8841-476f-a35c-3098246a828d
5
public void load() { String line, lineBeforeComment; String[] tokens; try { BufferedReader fin = new BufferedReader(new FileReader(fileName)); try { while ((line = fin.readLine()) != null) { tokens = line.split("#"); if (tokens.length > 0) { lineBeforeComment = tokens[0]; tokens = lineBeforeComment.split("="); if (tokens.length >= 2) keys.put(tokens[0], tokens[1]); } } } catch (IOException e) { e.printStackTrace(); } fin.close(); } catch (IOException e) { e.printStackTrace(); } }
b4998d3a-5b34-4b9f-a540-530018528caf
0
public static void main(String[] args) { String mango = "mango"; String s = "abc" + mango + "def" + 47; // StringBuilder sb = new StringBuilder(); // sb.append("abc"); // sb.append(mango); // sb.append("def"); // sb.append(47); // s = sb.toString(); System.out.println(s); }
c2364cde-a610-433c-adc2-005266af1416
3
private static void printGridletList(GridletList list, String name, boolean detail) { int size = list.size(); Gridlet gridlet = null; String indent = " "; System.out.println(); System.out.println("============= OUTPUT for " + name + " =========="); System.out.println("Gridlet ID" + indent + "STATUS" + indent + "Resource ID" + indent + "Cost"); // a loop to print the overall result int i = 0; for (i = 0; i < size; i++) { gridlet = (Gridlet) list.get(i); System.out.print(indent + gridlet.getGridletID() + indent + indent); System.out.print( gridlet.getGridletStatusString() ); System.out.println( indent + indent + gridlet.getResourceID() + indent + indent + gridlet.getProcessingCost() ); } if (detail == true) { // a loop to print each Gridlet's history for (i = 0; i < size; i++) { gridlet = (Gridlet) list.get(i); System.out.println( gridlet.getGridletHistory() ); System.out.print("Gridlet #" + gridlet.getGridletID() ); System.out.println(", length = " + gridlet.getGridletLength() + ", finished so far = " + gridlet.getGridletFinishedSoFar() ); System.out.println("======================================\n"); } } }
3e9d026c-96cf-496c-8b6f-9dc23b0291dd
9
public Map<Integer, Double> getRankedTagList(int userID, int resID) { Map<Integer, Double> resultMap = new LinkedHashMap<Integer, Double>(); if (this.userMaps != null && userID < this.userMaps.size()) { Map<Integer, Double> userMap = this.userMaps.get(userID); Map<Integer, Double> recMap = this.tagRecencies.get(userID); for (Map.Entry<Integer, Double> entry : userMap.entrySet()) { resultMap.put(entry.getKey(), entry.getValue().doubleValue() * recMap.get(entry.getKey()).doubleValue()); } } if (this.resMaps != null && resID < this.resMaps.size()) { Map<Integer, Double> resMap = this.resMaps.get(resID); for (Map.Entry<Integer, Double> entry : resMap.entrySet()) { Double val = resultMap.get(entry.getKey()); resultMap.put(entry.getKey(), val == null ? entry.getValue().doubleValue() : val.doubleValue() + entry.getValue().doubleValue()); } } // sort and return Map<Integer, Double> returnMap = new LinkedHashMap<Integer, Double>(); Map<Integer, Double> sortedResultMap = new TreeMap<Integer, Double>(new DoubleMapComparator(resultMap)); sortedResultMap.putAll(resultMap); int count = 0; for (Map.Entry<Integer, Double> entry : sortedResultMap.entrySet()) { if (count++ < 10) { returnMap.put(entry.getKey(), entry.getValue()); } else { break; } } return returnMap; }
4220bed9-81a2-482a-8e65-8d88e2b5e80e
8
public void clearEmptyLines(Set<Entry<String, List<String>>> entrySet) { for (Entry<String, List<String>> entry : finalFiles.entrySet()) { ArrayList<String> tempArray = new ArrayList<>(); tempArray.addAll(entry.getValue()); for (ListIterator<String> itr = tempArray.listIterator(); itr.hasNext(); ) { String element = itr.next(); if(StringUtils.isBlank(element) || StringUtils.isEmpty(element)) { // Checking for blank or empty lines itr.remove(); // remove them } else if (StringUtils.startsWith(element, " ") || StringUtils.endsWith(element, " ")) { element = element.trim(); } if (element.contains("\t")) { // Get rid of all the tabs String tempString = element.replaceAll("\\t", ""); if (tempString.length() > 0) { itr.set(tempString); } } } List<String> tempList = tempArray; finalFiles.put(entry.getKey(), tempList); // Replace the original List<String> } }
43dea56f-bd6e-44b6-9792-d496e1ebfbcf
6
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (!plugin.hasPerm(sender, "tp", false)) { sender.sendMessage(ChatColor.YELLOW + "You do not have permission to use /" + label); return true; } if (args.length == 0) { plugin.getServer().broadcastMessage("--Teleport Help--"); plugin.getServer().broadcastMessage("/tp [player]"); plugin.getServer().broadcastMessage("/tp [playera] [playerb]"); return true; } if (args.length == 1) { Player player = (Player) sender; if (plugin.playerMatch(args[0]) == null) { player.sendMessage(CraftEssence.premessage + "Player not found"); return true; } else { Player p = this.plugin.getServer().getPlayer(args[0]); player.teleport(p); sender.sendMessage(CraftEssence.premessage + "Teleporting to " + args[0] + "."); return true; } } if (args.length == 2) { Player a = this.plugin.getServer().getPlayer(args[0]); Player b = this.plugin.getServer().getPlayer(args[1]); a.teleport(b); if (plugin.isPlayer(sender)) sender.sendMessage(CraftEssence.premessage + "Teleporting " + args[0] + "to " + args[1] + "."); plugin.logger(Level.INFO, "Teleporting " + args[0] + " to " + args[1] + "."); } return false; }
1eb98231-1436-4198-81e1-ce265c19422d
4
@Override public String execute() throws Exception { try { Map session = ActionContext.getContext().getSession(); setUser((User) session.get("User")); Date date = new Date(); System.out.println("--------------------------------------------------" + existrate); System.out.println("------------------------------------------------------" + newrt); System.out.println("-------------------------------------------------------" + cfrt); if (existrate != null) { Adrate ad = (Adrate) myDao.getDbsession().get(Adrate.class, 1); ad.setCurrentRate(newrt); ad.setOldRate(existrate); ad.setDateChange(date); myDao.getDbsession().update(ad); // myDao.getDbsession().saveOrUpdate(ad); addActionMessage("New Rate Successfully Changed"); return "success"; } else { old = (Adrate) myDao.getDbsession().get(Adrate.class, 1); existrate = old.getCurrentRate(); Adrate ad = (Adrate) myDao.getDbsession().get(Adrate.class, 1); ad.setCurrentRate(newrt); ad.setOldRate(existrate); ad.setDateChange(date); myDao.getDbsession().update(ad); addActionMessage("New Rate Successfully Changed"); return "success"; } } catch (HibernateException e) { addActionError("Server Error Please Recheck All Fields "); e.printStackTrace(); return "error"; } catch (NullPointerException ne) { addActionError("Server Error Please Recheck All Fields "); ne.printStackTrace(); return "error"; } catch (Exception e) { addActionError("Server Error Please Recheck All Fields "); e.printStackTrace(); return "error"; } }
2cdaeb77-f99d-4174-9afc-34a7ae120a80
8
static Field getStaticField(Class<?> c,String key) throws DetectRightException { if (c == null) return null; if (Functions.isEmpty(key)) return null; Field f; try { f = c.getDeclaredField(key); return f; } catch (NoSuchFieldException e) { CheckPoint.checkPoint("Get Field 2" + key + " " + c.toString() + " " + e.toString()); } catch (SecurityException e) { CheckPoint.checkPoint(e.toString()); return null; } try { f = c.getField(key); return f; } catch (NoSuchFieldException e) { if (c.toString().equals("java.lang.String")) { //boolean dummy=true; } //DetectRight.checkPoint("Get Field 1" + key + " " + c.toString() + " " + e.toString()); return null; } catch (SecurityException e) { return null; } }
417814b0-04f8-4c89-931e-adc7808cb4c0
7
@Override public boolean execute(CommandSender sender, String[] args) { if(!(sender instanceof Player)) { return true; } String username = sender.getName(); String name = args[0]; Group group = groupManager.getGroupByName(name); if(group == null) { sender.sendMessage("Group doesn't exist"); return true; } Membership senderMembership = group.getMembership(username); boolean hasPermission = senderMembership != null && (senderMembership.isAdmin() || senderMembership.isModerator() || senderMembership.isMember()); if(!hasPermission) { sender.sendMessage("You don't have permission to perform this action"); return true; } for(Membership membership : group.getMemberships()) { Member member = membership.getMember(); sender.sendMessage(member.getName() + " " + membership.getRole()); } return true; }
ee9d4e81-816e-4550-aa9e-f8a348a9fe31
7
private void findMiddle(String s) { ArrayList<Integer> operations = new ArrayList<Integer>(); // compile the index of each operator for(int i = 0; i < s.length(); i++) { if( s.charAt(i) == OR || s.charAt(i) == AND || s.charAt(i) == IMPLY) { operations.add(i); } } // if there is only one operator, then just branch based off of that if(operations.size() == 1) { left = new Node(s.substring(0, operations.get(0))); right = new Node(s.substring(operations.get(0)+1)); root = s.charAt(operations.get(0)) + ""; } else { // go through each operator and check if it's the middle for(Integer i : operations) { if(isMiddle(s, i)) { left = new Node(s.substring(0, i)); right = new Node(s.substring(i+1)); root = s.charAt(i) + ""; break; } } } }
043e8639-0a98-41dd-9b7b-f21e669b853e
4
public Stability getLackingStabilityForType(DiscType discType){ LOGGER.log(Level.INFO, "Determining lacking stability rating for disc type " + discType); Bag tDiscs = getDiscsByType(discType); if (tDiscs.size() == 0) { return Stability.STABLE; } float stablePct = (float)(tDiscs.getDiscsWithStability(Stability.STABLE).size() * 100) / tDiscs.size(); float usPct = (float)(tDiscs.getDiscsWithStability(Stability.UNDERSTABLE).size() * 100) / tDiscs.size(); float osPct = (float)(tDiscs.getDiscsWithStability(Stability.OVERSTABLE).size() * 100) / tDiscs.size(); if (stablePct < MIN_STABILITY_PCT) { LOGGER.log(Level.INFO, "Lacking stability rating is STABLE."); return Stability.STABLE; } else if (usPct < MIN_STABILITY_PCT) { LOGGER.log(Level.INFO, "Lacking stability rating is UNDERSTABLE"); return Stability.UNDERSTABLE; } else if (osPct < MIN_STABILITY_PCT) { LOGGER.log(Level.INFO, "Lacking stability rating is OVERSTABLE"); return Stability.OVERSTABLE; } return Stability.UNKNOWN; }
6953a4b0-1036-4fc0-bcc2-84236abfb4b2
9
public Vector apply(Vector b, Vector x) { if (!(b instanceof DenseVector) || !(x instanceof DenseVector)) throw new IllegalArgumentException("Vectors must be a DenseVectors"); int[] rowptr = F.getRowPointers(); int[] colind = F.getColumnIndices(); double[] data = F.getData(); double[] bd = ((DenseVector) b).getData(); double[] xd = ((DenseVector) x).getData(); int n = F.numRows(); System.arraycopy(xd, 0, xx, 0, n); // Forward sweep (xd oldest, xx halfiterate) for (int i = 0; i < n; ++i) { double sigma = 0; for (int j = rowptr[i]; j < diagind[i]; ++j) sigma += data[j] * xx[colind[j]]; for (int j = diagind[i] + 1; j < rowptr[i + 1]; ++j) sigma += data[j] * xd[colind[j]]; sigma = (bd[i] - sigma) / data[diagind[i]]; xx[i] = xd[i] + omegaF * (sigma - xd[i]); } // Stop here if the reverse sweep was not requested if (!reverse) { System.arraycopy(xx, 0, xd, 0, n); return x; } // Backward sweep (xx oldest, xd halfiterate) for (int i = n - 1; i >= 0; --i) { double sigma = 0; for (int j = rowptr[i]; j < diagind[i]; ++j) sigma += data[j] * xx[colind[j]]; for (int j = diagind[i] + 1; j < rowptr[i + 1]; ++j) sigma += data[j] * xd[colind[j]]; sigma = (bd[i] - sigma) / data[diagind[i]]; xd[i] = xx[i] + omegaR * (sigma - xx[i]); } return x; }
a2246d79-34f1-4b8e-869b-10826e6147b4
8
private boolean isAlreadyExecuted() throws DomainToolsException{ boolean res = false; if(format.equals(DTConstants.JSON) && !responseJSON.isEmpty() || format.equals(DTConstants.HTML) && !responseHTML.isEmpty() || format.equals(DTConstants.XML) && !responseXML.isEmpty() || format.equals(DTConstants.OBJECT) && responseObject != null){ res=true; } return res; }
20d94262-f1e1-4dc6-b0ef-874c4758c519
1
public void visitAttribute(final Attribute attr) { checkEndMethod(); if (attr == null) { throw new IllegalArgumentException( "Invalid attribute (must not be null)"); } mv.visitAttribute(attr); }
21d4093e-9a4e-4a78-9968-f7ccca4d278f
3
/*package*/ static void init() { defaultProperty = new Properties(); defaultProperty.setProperty("weibo4j.debug", "true"); // defaultProperty.setProperty("weibo4j.source", Weibo.CONSUMER_KEY); //defaultProperty.setProperty("weibo4j.clientVersion",""); defaultProperty.setProperty("weibo4j.clientURL", "http://open.t.sina.com.cn/-{weibo4j.clientVersion}.xml"); defaultProperty.setProperty("weibo4j.http.userAgent", "weibo4j http://open.t.sina.com.cn/ /{weibo4j.clientVersion}"); //defaultProperty.setProperty("weibo4j.user",""); //defaultProperty.setProperty("weibo4j.password",""); defaultProperty.setProperty("weibo4j.http.useSSL", "false"); //defaultProperty.setProperty("weibo4j.http.proxyHost",""); defaultProperty.setProperty("weibo4j.http.proxyHost.fallback", "http.proxyHost"); //defaultProperty.setProperty("weibo4j.http.proxyUser",""); //defaultProperty.setProperty("weibo4j.http.proxyPassword",""); //defaultProperty.setProperty("weibo4j.http.proxyPort",""); defaultProperty.setProperty("weibo4j.http.proxyPort.fallback", "http.proxyPort"); defaultProperty.setProperty("weibo4j.http.connectionTimeout", "20000"); defaultProperty.setProperty("weibo4j.http.readTimeout", "120000"); defaultProperty.setProperty("weibo4j.http.retryCount", "3"); defaultProperty.setProperty("weibo4j.http.retryIntervalSecs", "10"); //defaultProperty.setProperty("weibo4j.oauth.consumerKey",""); //defaultProperty.setProperty("weibo4j.oauth.consumerSecret",""); defaultProperty.setProperty("weibo4j.async.numThreads", "1"); defaultProperty.setProperty("weibo4j.clientVersion", Version.getVersion()); try { // Android platform should have dalvik.system.VMRuntime in the classpath. // @see http://developer.android.com/reference/dalvik/system/VMRuntime.html Class.forName("dalvik.system.VMRuntime"); defaultProperty.setProperty("weibo4j.dalvik", "true"); } catch (ClassNotFoundException cnfe) { defaultProperty.setProperty("weibo4j.dalvik", "false"); } DALVIK = getBoolean("weibo4j.dalvik"); String t4jProps = "weibo4j.properties"; boolean loaded = loadProperties(defaultProperty, "." + File.separatorChar + t4jProps) || loadProperties(defaultProperty, Configuration.class.getResourceAsStream("/WEB-INF/" + t4jProps)) || loadProperties(defaultProperty, Configuration.class.getResourceAsStream("/" + t4jProps)); }
9e65e5f1-4724-42f5-9091-16e63823d567
2
public Polynomial monic() throws Exception { if (coeff.length == 0) return this; // 0 if (head() == 1L) return this; // already monic return mul(PF.inv(head())); }
1fd786c9-a894-45ec-9dd1-abb2e11a03ad
8
@Override protected void initiate() { // Create a menu to add all of the input fields into menu = new TMenu(0, 0, Main.canvasWidth / 4, Main.canvasHeight, TMenu.VERTICAL); menu.setBorderSize(5); add(menu); // Simulation parameters depthNumberField = new TNumberField(0, 0, 125, 25, 4); // limited to 4 digits long depthNumberField.setText("10"); mixedDepthNumberField = new TNumberField(0, 0, 125, 25, 4); // limited to 4 digits long mixedDepthNumberField.setText("5"); paceNumberField = new TNumberField(0, 0, 125, 25, 3); // limited to 3 digits long paceNumberField.setText("20"); // Particle parameters particleNumberField = new TNumberField(0, 0, 125, 25, 8); // limited to 8 digits long particleNumberField.setText("10000"); // Chunk parameters (a chunk is a subsection of the simulation) chunkNumberField = new TNumberField(0, 0, 125, 25, 4); // limited to 4 digits long chunkNumberField.setText("10"); // Add the components to a menu that automatically arranges everything on screen ~~~~~~~~~~ // Simulation parameters menu.add(new TLabel(" Depth of Simulation (meters): "), false); menu.add(depthNumberField, false); menu.add(new TLabel(" Depth of Mixed Layer (meters): "), false); menu.add(mixedDepthNumberField, false); menu.add(new TLabel(" Timestep of simulation (minutes): "), false); menu.add(paceNumberField, false); // Particle parameters menu.add(new TLabel(" Number of Particles: "), false); menu.add(particleNumberField, false); // Chunks (a chunk is a subsection of the simulation) menu.add(new TLabel(" Number of Chunks per meter: "), false); menu.add(chunkNumberField, false); menu.add(totalChunks, false); // Add a button that will begin the simulation when pressed. menu.add(new TButton("Start") { // Tell the button what to do when it is pressed @Override public void pressed() { double depth = depthNumberField.getValue(); double mixedLayerDepth = mixedDepthNumberField.getValue(); double pace = paceNumberField.getValue(); double numParticles = particleNumberField.getValue(); double chunks = chunkNumberField.getValue(); // Check that all parameters are reasonable, if not warn user // Depth of Simulation if (depth <= 0) { WindowTools.informationWindow("Warning - The depth must be: \n -Greater than 0m", "Cannot start Simulation"); return; // Don't start the simulation yet } // Depth of Mixed Layer if (mixedLayerDepth > depth) { WindowTools.informationWindow("Warning - The depth of the mixed layer must be: \n -Less than or equal to the depth of the Simulation", "Cannot start Simulation"); return; // Don't start the simulation yet } // Pace of simulation if (pace <= 0) { WindowTools.informationWindow("Warning - The pace must be: \n -Greater than 0", "Cannot start Simulation"); return; // Don't start the simulation yet } // Particle number if (particleNumberField.getValue() != Math.floor(particleNumberField.getValue())/* not a whole number */|| /* or less than 1 */particleNumberField.getValue() < 1) { WindowTools.informationWindow("Warning - The number of particles must be: \n -A whole number \n -Greater than 0", "Cannot start Simulation"); return; // Don't start the simulation yet } // Chunk number if (chunkNumberField.getValue() != Math.floor(chunkNumberField.getValue())/* not a whole number */|| /* or less than 1 */chunkNumberField.getValue() < 1) { WindowTools.informationWindow("Warning - The number of chunkis must be: \n -A whole number \n -Greater than 0", "Cannot start Simulation"); return; // Don't start the simulation yet } // Create a new simulation using the parameters set by the user. Main.sim = new Simulation(1/* width set to 1 meter */, (int) depth, (int) mixedLayerDepth, (int) pace, (int) numParticles, 1.0 / chunks); // Make the Simulation the current screen, instead of this ParameterInput. changeRenderableObject(Main.sim); } }); // end of adding the start button to the menu // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ if (Main.DEBUG) { menu.add(new TLabel("Debugging Tools"), false); menu.add(new TButton("Test Vector Field (2D)") { @Override public final void pressed() { changeRenderableObject(new VectorFieldTester()); } }); } }
50a4a101-8853-4540-8040-74c2085ddc93
4
public static void main(String Args[]) { int i = 0; long l = 0; for (i = 0; i < perfectarray.length; i++) { // l = i * i; // if (issquaredigitsquare(l)) { array[perfectarray[i]] = true; // System.out.println(perfectarray[i]); // System.out.print(","); // } } Scanner sr = new Scanner(System.in); int t = sr.nextInt(); int answer = 0; long a = 0; long b = 0; long k = 0; while (t > 0) { a = (int) Math.sqrt(sr.nextLong()); b = (int) Math.sqrt(sr.nextLong()); for (k = a; k < (b + 1); k++) { if (array[(int) k] == true) { answer++; } } //answer++; System.out.println(answer); answer = 0; t--; } return; }
cab54bb9-2827-41f0-aece-b21116f1a330
3
public static String getStackTrace(Exception ex) { if (ex == null) { return ""; } Object [] traces = ex.getStackTrace(); if (traces == null) { return ""; } String s = ""; for (Object trace : traces) { s += " " + trace.toString() + "\r\n"; } return s + "\r\n"; }
bd7c1ec8-b698-4560-bfa8-a48a625db2c5
2
public static boolean isBetween(int value, int lowLimit, int highLimit) { boolean between = false; if (value >= lowLimit && value < highLimit) { between = true; } return between; }
6ff09fe5-67f5-4ab1-abf0-5af499a3e0d4
1
public void writeCorpusToFile(String fileName) throws IOException { BufferedWriter out = new BufferedWriter(new FileWriter(new File(fileName))); out.write("<?xml version='1.0' encoding='UTF-8'?>"); out.write("\n<corpus corpusname=\"tagged-corpus\">"); out.write("\n\t<head>"); out.write("\n\t</head>"); out.write("\n\t<body>"); for (Sentence sentence : sentences) { out.write(sentence.toString()); } out.write("\n\t</body>"); out.write("\n</corpus>"); out.close(); }
0aa89be3-3b1a-41d6-b60d-554bc3d3ff1a
5
private void pickRandomQuote(MessageEvent<PircBotX> event) { try { if (!file.exists()) { System.out.println(file.createNewFile()); } FileReader fw = new FileReader(file); BufferedReader reader = new BufferedReader(fw); String line; Random random = new Random(); int i = 0; while ((line = reader.readLine()) != null){ if(line != null){ i++; } } i = random.nextInt(i-1); if(FileUtils.readLines(file).get(i)!=null){ MessageSending.sendNormalMessage(FileUtils.readLines(file).get(i).toString(), event); } } catch (IOException e) { e.printStackTrace(); } }
5fffdbd8-5b44-468b-8b3e-c337f733996f
7
private boolean isBlocking(float _x, float _y, float xa, float ya) { int x = (int) (_x / 16); int y = (int) (_y / 16); if (x == (int) (this.x / 16) && y == (int) (this.y / 16)) return false; boolean blocking = world.level.isBlocking(x, y, xa, ya); byte block = world.level.getBlock(x, y); if (((Level.TILE_BEHAVIORS[block & 0xff]) & Level.BIT_PICKUPABLE) > 0) { Mario.getCoin(); world.sound.play(Art.samples[Art.SAMPLE_GET_COIN], new FixedSoundSource(x * 16 + 8, y * 16 + 8), 1, 1, 1); world.level.setBlock(x, y, (byte) 0); for (int xx = 0; xx < 2; xx++) for (int yy = 0; yy < 2; yy++) world.addSprite(new Sparkle(x * 16 + xx * 8 + (int) (Math.random() * 8), y * 16 + yy * 8 + (int) (Math.random() * 8), 0, 0, 0, 2, 5)); } if (blocking && ya < 0) { world.bump(x, y, large); } return blocking; }
14aa66b5-43ea-4c2c-b846-a7e678c4a1e5
7
public void tableChanged(TableModelEvent e) { boolean dirty = !isSorted(); // Dirty bit to see if we should resort if (!dirty) { if (e.getType() == TableModelEvent.UPDATE) { if (e.getFirstRow() == TableModelEvent.HEADER_ROW) { // Table structure changed. Not supported for now! throw new UnsupportedOperationException( "SortedJTypeTableModel cannot handle table structure changes!!!"); } int col = e.getColumn(); if (col == TableModelEvent.ALL_COLUMNS) { // One of our columns is sorted dirty = true; } else if (e.getFirstRow() != e.getLastRow()) { // See if there's more than one row. // We could fire individual events for each row changed, but // we'll just be lazy and mark the dirty bit. dirty = true; } else { // See if we're changing any sorted columns if (spec.getSortDir(col) != 0) dirty = true; // for (SortCol sc : spec.getSortCols()) { // if (sc.col == col) { // dirty = true; // break; // } // } } } else { // It's INSERT or DELETE --- set dirty bit! dirty = true; } } if (dirty) { setSorted(); fireTableChanged(new TableModelEvent(this)); } else { // Re-work old event fireTableChanged(new TableModelEvent(this, modelToView[e.getFirstRow()], modelToView[e.getLastRow()], e.getColumn(), e.getType())); } }
7c595c0b-755a-4442-a7e2-11a2a87227d2
8
@Override public final void run() { if (shutdown) { CTT.debug("Attempting to shutdown game " + getGameId() + " again"); plugin.getServer().getScheduler().cancelTask(taskID); return; } signTracker++; if (signTracker == 2) { signTracker = 0; updateGameSign(); } if (playerlist.size() == 0 && gamestage != defaultStage) { CTT.debug("Set game " + getGameId() + " to not running because there aren't any more players, setting to default game stage: " + defaultStage); setGameStage(defaultStage); setRunning(false); } if (!running && playerlist.size() > 0) { setRunning(true); } if (!running) { idleRun(); } if (running) { gameRun(); } }
7f6321b4-a250-4871-8a44-f4db601c060b
2
private void initialize() { int padding = 5; joinChatPressed = false; agent = new MenuAgent(this); double ratio = (1.0+Math.sqrt(5.0))/2.0; Dimension screenDims = Toolkit.getDefaultToolkit().getScreenSize(); joinAction = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (joinButton.isEnabled()) joinChat(); else joinChatPressed = true; } }; addWindowListener(new WindowListener() { @Override public void windowActivated(WindowEvent e) { } @Override public void windowClosed(WindowEvent e) { } @Override public void windowClosing(WindowEvent e) { } @Override public void windowDeactivated(WindowEvent e) { } @Override public void windowDeiconified(WindowEvent e) { } @Override public void windowIconified(WindowEvent e) { } @Override public void windowOpened(WindowEvent e) { agent.connect(); } }); addWindowFocusListener(new WindowFocusListener() { @Override public void windowGainedFocus(WindowEvent arg0) { nameField.requestFocusInWindow(); } @Override public void windowLostFocus(WindowEvent arg0) { } }); JPanel panel = new JPanel(); panel.setLayout(null); double width = screenDims.width/4; Dimension panelDims = new Dimension((int)(width),(int)(width*ratio)); panel.setPreferredSize(panelDims); panel.setMaximumSize(panelDims); panel.setMinimumSize(panelDims); JLabel title = new JLabel("CaskChat"); title.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 30)); title.setSize(140,25); title.setLocation((panelDims.width - title.getWidth())/2,10); panel.add(title); statusBox = new JLabel(); statusBox.setHorizontalAlignment(SwingConstants.CENTER); statusBox.setSize(3*panelDims.width/4,20); statusBox.setLocation((panelDims.width - statusBox.getWidth())/2,title.getY() + title.getHeight() + padding); panel.add(statusBox); nameField = new JTextField(); nameField.setSize(100,20); nameField.setLocation((panelDims.width - nameField.getWidth())/2,panelDims.height/2); nameField.getDocument().addDocumentListener(new DocumentListener() { public void changedUpdate(DocumentEvent e) { nameChanged(); } @Override public void insertUpdate(DocumentEvent e) { nameChanged(); } @Override public void removeUpdate(DocumentEvent e) { nameChanged(); } }); nameField.addActionListener(joinAction); panel.add(nameField); nameStatus = new JLabel(); nameStatus.setHorizontalAlignment(SwingConstants.CENTER); nameStatus.setSize(150,20); nameStatus.setLocation((panelDims.width - nameStatus.getWidth())/2,nameField.getY() + nameField.getHeight() + padding); panel.add(nameStatus); joinButton = new JButton("Join Chat"); joinButton.setSize(100,20); joinButton.setLocation((panelDims.width - joinButton.getWidth())/2,3*panelDims.height/4); joinButton.addActionListener(joinAction); joinButton.setEnabled(false); panel.add(joinButton); JLabel versionLabel = new JLabel("v"+Parameters.VERSION_ID); versionLabel.setHorizontalAlignment(SwingConstants.CENTER); versionLabel.setSize(100,20); versionLabel.setLocation((panelDims.width - versionLabel.getWidth())/2,panelDims.height - versionLabel.getHeight()); panel.add(versionLabel); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new BorderLayout()); add(panel,BorderLayout.CENTER); pack(); if (System.getProperty("os.name").contains("Windows")) setSize(getWidth()-10,getHeight()-10); setResizable(false); setLocationRelativeTo(null); this.setVisible(true); }
a280e72a-2211-4995-adad-51b048c2125d
1
final int countIgnoredTests(final Xpp3Dom results) { final AtomicInteger ignored = new AtomicInteger(); new ForAllTestCases(results) { @Override void apply(Xpp3Dom each) { final String result = each.getChild("result").getValue(); ignored.addAndGet(result.equals(TestState.blocked.getState()) ? 1 : 0); } }.run(); return ignored.intValue(); }
c58c73cd-cc3d-4596-a52f-5387d3580820
2
@Override public boolean equals(Object obj) { if (obj instanceof Vector) { Vector v = (Vector) obj; return x == v.x && y == v.y; } return false; }
569c1f62-f71c-4547-bad4-a4346f425a8f
1
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true) private void onVehicleLeave(VehicleExitEvent event) { if(mResetTicksLived) event.getVehicle().setTicksLived(0); }
a9a38c01-515d-4c82-bff9-f21cd47c8f83
7
boolean performAndOrShortcut(Node a, Node b) { if (b.getInEdges().size() != 1) return false; if (b.block.getChildCount() > 0) { // Node b is not a mere conditional. return false; } ConditionalEdge aToC; ConditionalEdge bToC; boolean isOR = true; while(true) { aToC = a.getConditionalEdge(isOR); bToC = b.getConditionalEdge(isOR); if (bToC.target == aToC.target) break; if (!isOR) return false; isOR = false; } if (aToC.target.getInEdges().size() != 2) return false; ConditionalEdge bToD = b.getConditionalEdge(!isOR); ConditionalEdge aToB = a.getConditionalEdge(!isOR); aToB.redirect(bToD.target); removeEdge(bToC); removeEdge(bToD); removeNode(b); InfixExpression infix = new InfixExpression( isOR?InfixExpression.Operator.CONDITIONAL_OR:InfixExpression.Operator.CONDITIONAL_AND); // Note that the order aToC, then bToC is important. infix.setOperands( aToC.getBooleanExpression().getExpression(), bToC.getBooleanExpression().getExpression()); BooleanExpression be = new BooleanExpression(infix); aToC.setBooleanExpression(be); aToB.setBooleanExpression(be); logger.debug("Created shortcut and removed " + b); return true; }
3a22e539-1f56-4a99-b3ae-96592932266f
1
public void addAssociation(Association a) { if(!associationsSet.contains(a)) { associationsList.add(a); associationsSet.add(a); } }
8d9edebe-f8db-4584-96cf-73ca50c89d84
3
public void setValor(PValor node) { if(this._valor_ != null) { this._valor_.parent(null); } if(node != null) { if(node.parent() != null) { node.parent().removeChild(node); } node.parent(this); } this._valor_ = node; }
94bae2f7-ab1e-40d0-b9fb-beb3c01ccedf
6
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Vista.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Vista.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Vista.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Vista.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Vista().setVisible(true); } }); }
324af607-9c59-4ba9-8892-2ce58ec4142c
3
public static void sort(int[] array) { printArray(array); int index = 0; int tmp = array[0]; int j; for (int i = 0; i < array.length - 1; i++) { index = 0; tmp = array[0]; for (j = 1; j < array.length - i; j++) { if(tmp < array[j]) { index = j; tmp = array[j]; } } j--; array[index] = array[j]; array[j] = tmp; printArray(array); } }
bb12f049-1700-44f5-a603-7cf1c6e93811
8
public JSONObject executeBasic() throws CloudflareError { try { HttpPost post = new HttpPost( CloudflareAccess.CF_API_LINK); post.setEntity(new UrlEncodedFormEntity(post_values)); HttpResponse response = api.getClient().execute(post); BufferedReader rd = new BufferedReader(new InputStreamReader( response.getEntity().getContent())); StringBuilder sbResult = new StringBuilder(); String line = null; while ((line = rd.readLine()) != null) { sbResult.append(line); } line = null; JSONObject jsonResult = (JSONObject) JSONSerializer.toJSON( sbResult.toString()); sbResult = null; if (!jsonResult.containsKey("result")) { throw new CloudflareError("no_result", "No result received", "Result=null"); } CloudflareResult result = CloudflareResult.valueOf(jsonResult.getString( "result")); switch (result) { case success: { if (jsonResult.containsKey("response")) { return jsonResult.getJSONObject("response"); } else { return jsonResult; } } case error: { String errMessage = "(no message in response)"; if (jsonResult.containsKey("msg")) { errMessage = jsonResult.getString("msg"); } String errCode = CloudflareErrorEnum.UNKNOWN_ERROR.toString(); if (jsonResult.containsKey("err_code")) { errCode = jsonResult.getString("err_code"); } throw CloudflareErrorEnum .valueOf(errCode) .getException(errMessage); } } } catch (IOException e) { } return null; }
6c258990-9717-469f-8774-98c8ea00185d
3
public void save() { SortedMap<String,String> sortedKeys = new TreeMap<String,String>(keys); try { BufferedWriter output = new BufferedWriter(new FileWriter(fileName)); try { for (String key : sortedKeys.keySet()) output.write(key.toLowerCase() + "=" + sortedKeys.get(key) + newLine); } catch (IOException e) { e.printStackTrace(); } output.close(); } catch (IOException e) { e.printStackTrace(); } }
9239735e-49ad-460d-bed1-069e16698dca
2
public long getLong(String key) throws JSONException { Object object = this.get(key); try { return object instanceof Number ? ((Number) object).longValue() : Long.parseLong((String) object); } catch (Exception e) { throw new JSONException("JSONObject[" + quote(key) + "] is not a long."); } }
8defdef1-95af-41d3-881c-f9eb43db80a5
1
public void newProduct() { try { Database db = dbconnect(); String query = "INSERT INTO product (name, description) VALUES " + "(?,?)"; db.prepare(query); db.bind_param(1, this.name); db.bind_param(2, this.description); db.executeUpdate(); db.close(); } catch(SQLException e){ Error_Frame.Error(e.toString()); } }
45506a2e-a5dc-4177-9f77-54d10a61a519
5
*/ private boolean isInstDefault() { if (instCheck.size() == 0) { return false; } for (Iterator j=instCheck.keySet().iterator(); j.hasNext(); ) { String key = (String)j.next(); if ( isDefaultInst(key) ) { // デフォルト装置種別の場合 if ( !((JCheckBox)instCheck.get(key)).isSelected() ) { return false; } } else { if ( ((JCheckBox)instCheck.get(key)).isSelected() ) { return false; } } } return true; }
bb96a7de-dc7e-4045-95b6-0febab14861e
1
public ArrayList<GradeItem> gradeItems(ResultSet rs) throws Exception { DBConnector db = new DBConnector(); ArrayList<GradeItem> data = new ArrayList<>(); while (rs.next()) { data.add(new GradeItem(db.getGradeItem(rs.getInt("gradeitemid")))); } return data; }
b78452f0-3466-4614-bc27-ec70dc971eda
2
public static Utilisateur selectById(int id) throws SQLException { String query = null; Utilisateur util = new Utilisateur(); ResultSet resultat; try { query = "SELECT * from UTILISATEUR where ID_UTILISATEUR=? "; PreparedStatement pStatement = ConnectionBDD.getInstance().getPreparedStatement(query); pStatement.setInt(1, id); resultat = pStatement.executeQuery(); while (resultat.next()) { util = new Utilisateur(resultat.getInt("ID_UTILISATEUR"), resultat.getInt("ID_FONCTION"), resultat.getInt("ID_VILLE"), resultat.getString("UTILNOM"), resultat.getString("UTILPRENOM"), resultat.getString("IDENTIFIANT"), resultat.getString("PASSWORD")); } } catch (SQLException ex) { Logger.getLogger(RequetesUtilisateur.class.getName()).log(Level.SEVERE, null, ex); } return util; }
f50fd98f-3be3-4d50-9953-4f30f15fc15f
6
@Override public void mouseMoved(MouseEvent e) { Point p = e.getPoint(); Point imageOrigin = getImageLoc(); if(p != null && bufImage != null){ Point imagePixel = new Point(p); imagePixel.x -= imageOrigin.x; imagePixel.y -= imageOrigin.y; if(imagePixel.x >= bufImage.getWidth() || imagePixel.x < 0) return; if(imagePixel.y >= bufImage.getHeight() || imagePixel.y < 0) return; int val = bufImage.getRGB((int)imagePixel.getX(), (int)imagePixel.getY()); pixelRField.setText("" + (val & 0x000000FF)); pixelGField.setText("" + ((val & 0x0000FF00)>>8) ); pixelBField.setText("" + ((val & 0x00FF0000)>>16) ); } }
b4e7125b-8d88-4fbd-be96-a762c757c937
8
public static PostingsList andMerge(PostingsList posting1, PostingsList posting2) { PostingsList merged = new PostingsList(); if (posting1 != null && posting2 != null && posting1.size() > 0 && posting2.size() > 0) { Node p1 = posting1.head; Node p2 = posting2.head; while (p1 != null && p2 != null) { if (p1.docID() == p2.docID()) { // we found a match, so add it to the list merged.addDoc(p1.docID()); p1 = p1.next(); p2 = p2.next(); } else if (p1.docID() < p2.docID()) { // move up p1 p1 = p1.next(); } else { // move up p2 p2 = p2.next(); } } } return merged; }
0e84dc39-0608-4314-9315-e2987c86d572
4
public boolean collides(int x, int y){ //CHECKS IF PASSED X Y COORDS COLLIDE WITH THE BLOCK if(x >= this.x && x <= this.x + this.width && y >= this.y && y <= this.y + this.height){ return true; } return false; }
f8524188-4212-4680-b7f2-8c5d3affd595
5
static void analyze(Object obj) { Class clazz = obj.getClass(); String name = clazz.getName(); System.out.println(name); Constructor[] constructors = clazz.getConstructors(); for (Constructor c : constructors) { System.out.println("Constructor name: " + c.getName()); } Field[] fields = clazz.getFields(); for (Field f : fields) { System.out.println("field: " + f.getName()); } Field[] declaredFields = clazz.getDeclaredFields(); for (Field f : declaredFields) { System.out.println("declared field:" + f.getName()); } Method[] methods = clazz.getMethods(); for (Method m : methods) { System.out.println("method: " + m.getName()); } Method[] declaredMethods = clazz.getDeclaredMethods(); for (Method m : declaredMethods) { System.out.println("declared method: " + m.getName()); } }
cd8da66a-d7e9-4277-a993-b7d49b1b6aa2
9
private void processTextFile(File file) { BufferedReader is = null; PrintWriter pw = null; TextModes modes = new TextModes(); try { pw = new PrintWriter(file.getAbsolutePath().replace(REMOVE_FROM_PATH, "")); is = new BufferedReader(new FileReader(file)); String aline; List<String> lines = new ArrayList<>(); while ((aline = is.readLine()) != null) { lines.add(aline); } List<String> outLines = processTextFileLines(lines, file, modes); for (String modLine : outLines) { pw.println(modLine); } } catch (IOException e) { System.err.printf("I/O Error on %s: %s%n", file, e); } finally { if (modes.fileChanged) { log.info(file + " had change(s)"); // XXX run diff? } if (modes.inCutMode) { System.err.println("WARNING: " + file + " file ends in cut mode!"); } if (modes.inCommentMode) { System.err.println("WARNING: " + file + " file ends in commenting-out mode!"); } if (is != null) { try { is.close(); } catch (IOException annoyingLittleCheckedException) { annoyingLittleCheckedException.printStackTrace(); } } if (pw != null) { pw.close(); } } }
e3a1ba32-4e8f-4429-9bfe-dc36d6c90726
5
public String getResult(){ String display = new String(); int n = 0; display = ""; if(this.valorCliente>0){ this.valorTroco = this.valorCliente; if(this.valorTroco>=50){ n = (int)(this.valorTroco/50); this.valorTroco-= n*50; }//END IF display += n+" "; n = 0; if(this.valorTroco>=10){ n = (int)(this.valorTroco/10); this.valorTroco-= n*10; }//END IF display += n+" "; n = 0; if(this.valorTroco>=5){ n = (int)(this.valorTroco/5); this.valorTroco-= n*5; }//END IF display += n+" "; n = 0; if(this.valorTroco>=1){ n = (int)(this.valorTroco/1); this.valorTroco-= n; }//END IF display += n; }//END IF return display; }//END FUNCTION
cf980c51-9895-4e35-932d-5c676f2c77a8
4
public static void delete(File src) throws IOException { if (!src.exists()) return; if (!src.isDirectory()) { src.delete(); return; } for (File f : src.listFiles()) { if (f.isDirectory()) delete(f); f.delete(); } }
ec831b38-dfa9-4441-96c1-401cd631fe13
7
public double olbStart() { sortResources(); sortClass(); calculateWeight(); System.out.println(iCPUMaxNum); dmMinminCost = new double[iSite][iCPUMaxNum]; dmMinminTime = new double[iSite][iCPUMaxNum]; double[] daMinminTimeBySite = new double[iSite]; // find the current cheapest site for the acitvities. int k = 0; while (getRestLength() > 0) { k = Math.round(Math.round(Math.random() * (iClass + 1))) % iClass; if (iaQueuedTask[k] > 0) { iMinClass = k; findMinCompleteCPU(); iaQueuedTask[k]--; updateMin(); iStage++; } } double sumTime = 0, sumCost = 0; int xMaxTime = 0, yMaxtime = 0; double tmpTime = -1; for (int i = 0; i < iSite; i++) { for (int j = 0; j < iaCPU[i]; j++) { daMinminTimeBySite[i] += dmMinminTime[i][j]; // find cpu with the maximum execution time if (dmMinminTime[i][j] > tmpTime) { xMaxTime = i; yMaxtime = j; tmpTime = dmMinminTime[i][j]; } sumTime += dmMinminTime[i][j]; sumCost += dmMinminCost[i][j]; } } for (int i = 0; i < iClass; i++) { // System.out.print(iStage + "Distribution[" + i + "]"); for (int j = 0; j < iSite; j++) { // System.out.print(dmDistribution[i][j] + ", "); } // System.out.println(); } calculateOtherSchedulingEfficiency(); System.out.println("Fairness = " + calculateFairness()); System.out.println("OLB Time = " + sumTime); System.out.println("MakeSpan = " + tmpTime); dCost = sumCost; dTime = sumTime; dFinalMakespan = tmpTime; return sumTime; }
b025cedf-4309-40f0-86da-f3edfdb4cb2c
9
public static List<MeasureSite> findAllMeasureSite() { List<MeasureSite> measureSiteList = new ArrayList<MeasureSite>(); MeasureSite measureSite = null; ResultSet rs = null; Statement stmt = null; Connection conn = null; try { // new oracle.jdbc.driver.OracleDriver(); // jdbc.url=jdbc\:oracle\:thin\:@192.168.72.99\:1521\:orcl // jdbc.username=lkmes2 // jdbc.password=lkmes2 Properties prop = new Properties();// 属性集合对象 // FileInputStream fis = new FileInputStream("jdbc.properties");// 属性文件流 InputStream fis = Thread.currentThread().getContextClassLoader().getResourceAsStream("jdbc.properties"); prop.load(fis);// 将属性文件流装载到Properties对象中 String driverClassName = prop.getProperty("jdbc.driverClassName"); // jdbc.url=jdbc\:oracle\:thin\:@10.1.11.222\:1521\:orcl String url = prop.getProperty("jdbc.url"); // jdbc.username=lkmes2 String username = prop.getProperty("jdbc.username"); // jdbc.password=lkmes2 String password = prop.getProperty("jdbc.password"); Class.forName(driverClassName); conn = DriverManager.getConnection(url, username, password); stmt = conn.createStatement(); rs = stmt.executeQuery("select * from MES_MME_MEASURE_SITE"); while (rs.next()) { System.out.println("#####"); measureSite = new MeasureSite(); // SID NUMBER(15) NOT NULL, long sid = rs.getLong("sid"); System.out.println(sid); measureSite.setSid(sid); // METER_NAME VARCHAR2(40 BYTE), String meterName = rs.getString("METER_NAME"); System.out.println(meterName); measureSite.setMeterName(meterName); // IP VARCHAR2(40 BYTE), String ip = rs.getString("IP"); System.out.println(ip); measureSite.setIp(ip); // SITE_NO VARCHAR2(32 BYTE) NOT NULL, String siteNo = rs.getString("SITE_NO"); System.out.println(siteNo); measureSite.setIp(ip); // SITE_NAME VARCHAR2(64 BYTE) NOT NULL, String siteName = rs.getString("SITE_NAME"); System.out.println(siteName); measureSite.setIp(ip); // SITE_TYPE VARCHAR2(3 BYTE), // ZERO_STANDARD VARCHAR2(10 BYTE), // CREATED_BY VARCHAR2(32 BYTE), // CREATED_DT DATE, // UPDATED_BY VARCHAR2(32 BYTE), // UPDATED_DT DATE, // VERSION NUMBER(9), // COM_PORT VARCHAR2(10 BYTE), String comPort = rs.getString("COM_PORT"); System.out.println(comPort); measureSite.setComPort(comPort); // COM_FREQUENCY NUMBER(8) int comFrequency = rs.getInt("COM_FREQUENCY"); System.out.println(comFrequency); measureSite.setComFrequency(comFrequency); measureSiteList.add(measureSite); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (rs != null) { rs.close(); rs = null; } if (stmt != null) { stmt.close(); stmt = null; } if (conn != null) { conn.close(); conn = null; } } catch (SQLException e) { e.printStackTrace(); } } return measureSiteList; }
0cfa7db7-1f19-44e0-9e92-6375358d1a1d
3
private void checkmappos() { if (cam == null) return; Coord sz = this.sz; SlenHud slen = ui.slenhud; if (slen != null) sz = sz.add(0, -slen.foldheight()); Gob player = glob.oc.getgob(playergob); if (player != null) cam.setpos(this, player, sz); }
b18bd98e-3670-4b73-a7c5-e3b86ea1fb71
3
public final void generateFiles(boolean internal) { // internal is true if called by onEnable and False if called by command if (internal && !generationFinished) { // 5 * 20 = 5 seconds (20 ticks per second) scheduler.scheduleSyncDelayedTask(this, new PermissionTask(this), 5 * 20L); } else if (!internal) { scheduler.scheduleSyncDelayedTask(this, new PermissionTask(this)); } }
da6cf275-734e-49aa-8991-82e797c87b97
9
private boolean replaceEvents(String key, Faction.FactionChangeEvent event, boolean strict) { final Faction.FactionChangeEvent[] events=changes.get(key); if(events==null) return false; final Faction.FactionChangeEvent[] nevents=new Faction.FactionChangeEvent[events.length-1]; int ne1=0; boolean done=false; for (final FactionChangeEvent event2 : events) { if((strict&&(event2 == event))||((!strict)&&(event2.toString().equals(event.toString())))) { if(nevents.length==0) changes.remove(key); else changes.put(key,nevents); done=true; } else if(ne1<nevents.length) nevents[ne1++]=event2; } if(done) abilChangeCache.clear(); return done; }
05b07465-3c88-4dea-aebc-6ba3830cadb3
9
public void run() { try { SocketChannel socketChannel = SocketChannel.open(); socketChannel.socket().setReceiveBufferSize( m_socketBufferSize ); StreamDefragger streamDefragger = new StreamDefragger(4) { protected int validateHeader( ByteBuffer header ) { return header.getInt(); } }; if (!socketChannel.connect(m_addr) || !socketChannel.finishConnect()) { System.out.println( "SocketChannel.connect() failed." ); return; } ByteBuffer bb = ByteBuffer.allocateDirect( m_socketBufferSize ); ByteBuffer startRequest = m_startRequest.duplicate(); final int bytesSent = socketChannel.write( startRequest ); if (bytesSent != startRequest.capacity()) { System.out.println( "SocketChannel.send() failed." ); return; } int messages = 0; int bytesReceivedTotal = 0; long startTime = 0; readSocketLoop: for (;;) { final int bytesReceived = socketChannel.read( bb ); if (bytesReceived > 0) { if (bytesReceivedTotal == 0) startTime = System.nanoTime(); bytesReceivedTotal += bytesReceived; bb.position( 0 ); bb.limit( bytesReceived ); ByteBuffer msg = streamDefragger.getNext( bb ); while (msg != null) { final int messageLength = msg.getInt(); assert( messageLength == m_messageLength ); if (++messages == m_messages) break readSocketLoop; msg = streamDefragger.getNext(); } bb.clear(); } } long entTime = System.nanoTime(); socketChannel.close(); System.out.println( "Received " + messages + " messages (" + bytesReceivedTotal + " bytes) at " + Util.formatDelay(startTime, entTime) + "." ); } catch (IOException ex) { ex.printStackTrace(); } }
4d065e7e-603e-457d-b1bd-6d065e821e2c
1
public static void assertNotNull(Object value, String errorMessage) throws BeanstreamApiException { // could use StringUtils.assertNotNull(); if (value == null) { // TODO - do we need to supply category and code ids here? BeanstreamResponse response = BeanstreamResponse.fromMessage("invalid payment request"); throw BeanstreamApiException.getMappedException(HttpStatus.SC_BAD_REQUEST, response); } }
14dd3e68-d9b2-41be-a8eb-3aa7991b1324
8
public SplashScreen() { setTitle("Board Games"); setResizable(false); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Set up the menu setJMenuBar(menuBar); menuBar.add(fileMenu); fileMenu.add(exit); menuBar.add(helpMenu); helpMenu.add(about); helpMenu.add(updates); // Set content pane JPanel mainPnl = new JPanel(new GridLayout(4, 1)); setContentPane(mainPnl); // Add content to the content pane JPanel inputPnl = new JPanel(new GridLayout(2, 2)); mainPnl.add(boardSizeLabel, BorderLayout.NORTH); inputPnl.add(rowsLabel); inputPnl.add(rowsField); inputPnl.add(colsLabel); inputPnl.add(colsField); mainPnl.add(inputPnl, BorderLayout.CENTER); JPanel gamesPnl = new JPanel(new FlowLayout()); gamesPnl.add(selectLabel); gamesPnl.add(gamesList); mainPnl.add(gamesPnl); mainPnl.add(playButton, BorderLayout.SOUTH); pack(); // Determine the new location of the window int x = ((screenSize.width - getContentPane().getSize().width) / 2); int y = ((screenSize.height - getContentPane().getSize().height) / 2); // Move the window setLocation(x, y); /* Add action listners */ playButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (!rowsField.getText().equals("") && !colsField.getText().equals("")) { Configuration.setBoardWidth(Integer.parseInt(rowsField.getText())); Configuration.setBoardHeight(Integer.parseInt(colsField.getText())); String game = Configuration.getGame(gamesList.getSelectedIndex()); if (game != null) { try { Class c = Class.forName("com.kbrahney.pkg.board.games." + game + ".GUI"); c.getDeclaredConstructor(int.class, int.class, char.class).newInstance(Configuration.getBoardWidth(), Configuration.getBoardHeight(), Configuration.getDefaultChar()); } catch (ClassNotFoundException ex) { Logger.getLogger(SplashScreen.class.getName()).log(Level.SEVERE, null, ex); } catch (InstantiationException ex) { Logger.getLogger(SplashScreen.class.getName()).log(Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { Logger.getLogger(SplashScreen.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchMethodException ex) { Logger.getLogger(SplashScreen.class.getName()).log(Level.SEVERE, null, ex); } catch (InvocationTargetException ex) { Logger.getLogger(SplashScreen.class.getName()).log(Level.SEVERE, null, ex); } } } } }); }
b337a581-bbb3-4547-adfe-ffaff62d9cf2
0
@Override public void applyCurrentToApplication() { // Apply any prefs to the app that won't be looked up directly from the preferences. }
7edf534c-8992-4c01-bc04-fbdfc2e07c51
2
private String join(String[] array, String separator) { if (array.length == 0) { return ""; } String ret = ""; for (int i = 0; i < array.length; i++) { ret += array[i] + separator; } return ret.substring(0, ret.length() - separator.length()); }
80bea09a-48af-41e7-a838-d2d96487d4da
4
public static JsonNode merge(JsonNode mainNode, JsonNode updateNode) { Iterator<String> fieldNames = updateNode.fieldNames(); while (fieldNames.hasNext()) { String fieldName = fieldNames.next(); JsonNode jsonNode = mainNode.get(fieldName); // if field doesn't exist or is an embedded object if (jsonNode != null && jsonNode.isObject()) { merge(jsonNode, updateNode.get(fieldName)); } else { if (mainNode instanceof ObjectNode) { // Overwrite field JsonNode value = updateNode.get(fieldName); ((ObjectNode) mainNode).put(fieldName, value); } } } return mainNode; }
699eec85-a6d2-46f5-8914-c834348dfaa0
4
public JButton getButton(int buttonType) { for (int a = 0; a < getComponentCount(); a++) { if (getComponent(a) instanceof JButton) { JButton button = (JButton) getComponent(a); Object value = button.getClientProperty(PROPERTY_OPTION); int intValue = -1; if (value instanceof Number) { intValue = ((Number) value).intValue(); } if (intValue == buttonType) { return button; } } } return null; }
0a43d140-89f6-4470-895e-d5698f2b4917
2
public abstractPage(){ super(new BorderLayout()); if ( lang.equals("en")) { //static Button appLang = new JButton("Arabic"); //welcomePage //--------Labels-------- appNameLabel = new JLabel("Parking Permit Kiosk"); appInfoLabel = new JLabel("This application issues parking permits for York University's students"); appVersionLabel = new JLabel("1.0"); progs = new JLabel("<html>"+"Created by: <br>" + "Aidan Waite <br>"+ "and <br>" + "Ahmad Aseeri"); //--------Buttons------- start = new JButton("Start"); //studentRecord //--------Info-------- studLabel = new JLabel("Studnet Records"); studInfoLabel = new JLabel("Checkes the stduents datebase wether they are eligible to issue a parking permit or not "); //--------Labels------- studIDLabel = new JLabel("Student number"); studPinLabel = new JLabel("Student pin"); studLastLabel = new JLabel("Last name"); studFirstLabel = new JLabel("First name"); studStatusLabel = new JLabel("Status"); //--------TextFields------- studID = new JTextField(""); studPin = new JTextField(""); studLast = new JTextField(""); studFirst = new JTextField(""); studStatus = new JTextField(""); //--------Buttons--------- studClear = new JButton("Clear"); studNext = new JButton("Next"); //parkingPermit //--------Info-------- parkLabel = new JLabel("Parking Permit"); parkInfoLabel = new JLabel("Issues a prking permit for the eligible student"); //--------Labels-------- parkStudIDLabel = new JLabel("Student number"); parkStudPinLabel = new JLabel("Student pin"); parkStudEmailLabel = new JLabel("Email"); parkCarMakeLabel = new JLabel("Make"); parkCarModelLabel = new JLabel("Model"); parkCarPlateLabel = new JLabel("Plate number"); parkCarInsuranceLabel = new JLabel("Insurance"); parkMonthLabel = new JLabel("Month"); parkYearLabel = new JLabel("Year"); //---------TextFields------ parkStudID = new JTextField(""); parkStudPin = new JTextField(""); parkStudEmail = new JTextField(""); parkCarMake = new JTextField(""); parkCarModel = new JTextField(""); parkCarPlate = new JTextField(""); parkCarInsurance = new JComboBox(); parkMonth = new JComboBox(); parkYear = new JComboBox(); //---------Buttons--------- parkStudCalculate = new JButton("Calculate"); parkStudCancel = new JButton("Cancel"); //PaymentApproved //--------Info-------- payLabel = new JLabel("Payment comfirmation"); payNoteLabel = new JLabel("<html>"+"Note: The total cost will be added to the "+"</br>"+"financial student account. The cost for each day is C$3.5"); //---------Labels-------- payTotalLabel = new JLabel("Total cost is: "); payPeriodLabel = new JLabel("Total period is: "); //---------TextFields-------- payTotal = new JTextField(""); payPeriod = new JTextField(""); //---------Buttons--------- payConfirm = new JButton("Confirm"); payCancel = new JButton("Cancel"); //ParkingCard //--------Info-------- parkCardLabel = new JLabel("Parking Permit Card"); parkCardInfoLabel = new JLabel("Student must applay the card inside the card"); //---------Labels-------- parkCardIDLabel = new JLabel("Parking permit ID:"); parkCardStudIDLabel = new JLabel("Student number:"); parkCardStudNameLabel = new JLabel("Studnet name:"); parkCardExpiredDateLabel = new JLabel("Expired date:"); parkCardBarcodeLabel = new JLabel("Barcode:"); //---------TextFields-------- parkCardID = new JLabel("### ## ###"); parkCardStudID = new JLabel("### ### ###"); parkCardStudName = new JLabel("____ ___ ______"); parkCardExpiredDate = new JLabel("May, 2014"); parkCardBarcode = new JLabel(""); //----------Buttons--------- parkCardNew = new JButton("New"); parkCardClose = new JButton("Close"); parkCardHist = new JButton("History"); } else if (lang.equals("ar")) { //static Button appLang = new JButton("English"); //welcomePage //--------Labels-------- appNameLabel = new JLabel("نطام اصدار تصريح المواقف"); appInfoLabel = new JLabel("برنامح تابع لجامغة يورك لاصدار تصريح المواقف للطلاب"); appVersionLabel = new JLabel("١,٠"); //--------Buttons------- start = new JButton("إبدأ"); //studentRecord //--------Info-------- studLabel = new JLabel("سجلات الطلاب"); studInfoLabel = new JLabel("للتأكد من قابلية الطالب لاصدار بطاقة تصريح موقف "); //--------Labels------- studIDLabel = new JLabel("رقم الطالب"); studPinLabel = new JLabel("الرقم السري"); studLastLabel = new JLabel("اسم العائلة"); studFirstLabel = new JLabel("الاسم الاول"); studStatusLabel = new JLabel("الحالة"); //--------TextFields------- studID = new JTextField(""); studPin = new JTextField(""); studLast = new JTextField(""); studFirst = new JTextField(""); studStatus = new JTextField(""); //--------Buttons--------- studClear = new JButton("مسح البيانات"); studNext = new JButton("التالي"); //parkingPermit //--------Info-------- parkLabel = new JLabel("اصدار تصريح الموقف"); parkInfoLabel = new JLabel("تعبئة بينات تصريح الموقف "); //--------Labels-------- parkStudIDLabel = new JLabel("رقم الطالب"); parkStudPinLabel = new JLabel("الرقم السري"); parkStudEmailLabel = new JLabel("البريد الالكتروني"); parkCarMakeLabel = new JLabel("نوع السيارة"); parkCarModelLabel = new JLabel("المودبل"); parkCarPlateLabel = new JLabel("رفم اللوحة"); parkCarInsuranceLabel = new JLabel("التأمين"); parkMonthLabel = new JLabel("الشهر"); parkYearLabel = new JLabel("الستة"); //---------TextFields------ parkStudID = new JTextField(""); parkStudPin = new JTextField(""); parkStudEmail = new JTextField(""); parkCarMake = new JTextField(""); parkCarModel = new JTextField(""); parkCarPlate = new JTextField(""); parkCarInsurance = new JComboBox(); parkMonth = new JComboBox(); parkYear = new JComboBox(); //---------Buttons--------- parkStudCalculate = new JButton("احسب"); parkStudCancel = new JButton("إلفاء الأمر"); //PaymentApproved //--------Info-------- payLabel = new JLabel("تأكيد الدفع"); payInfoLabel = new JLabel("سيتم احتساب ٣.٥ دولار كندي عن كل يوم. وسيتم اضافتها الى السحلات المالية للطالب"); //---------Labels-------- payTotalLabel = new JLabel("المجموع"); payPeriodLabel = new JLabel("المدة"); //---------TextFields-------- payTotal = new JTextField(""); payPeriod = new JTextField(""); //---------Buttons--------- payConfirm = new JButton("وافق"); payCancel = new JButton("إلغاء الأمر"); //ParkingCard //--------Info-------- parkCardLabel = new JLabel("بطاقة تصريح الموقف"); parkCardInfoLabel = new JLabel("يجب وضع البطاقة في مكان واضح داخل السيارة"); //---------Labels-------- parkCardIDLabel = new JLabel("رقم التصريح"); parkCardStudIDLabel = new JLabel("رقم الطالب"); parkCardStudNameLabel = new JLabel("اسم الطالب"); parkCardExpiredDateLabel = new JLabel("تاريخ الانتهاء"); parkCardBarcodeLabel = new JLabel("الباركود"); //---------TextFields-------- parkCardID = new JLabel(""); parkCardStudID = new JLabel(""); parkCardStudName = new JLabel(""); parkCardExpiredDate = new JLabel(""); parkCardBarcode = new JLabel(""); //----------Buttons--------- parkCardNew = new JButton("اصدار تصريح جديد"); parkCardClose = new JButton("إغلاق البرنامج"); } top = new JPanel(); center = new JPanel(new BorderLayout()); bottom = new JPanel(new BorderLayout()); }
cdab8583-42e4-4807-9d43-f0f344066c98
2
private static int[] portRangeToArray(int portMin, int portMax) { if (portMin > portMax) { int tmp = portMin; portMin = portMax; portMax = tmp; } int[] ports = new int[portMax - portMin + 1]; for (int i = 0; i < ports.length; i++) ports[i] = portMin + i; return ports; }
ef5c11ca-dc01-430d-acaf-02f60f9cc8f9
0
public void setBytes(byte[] bytes) { this.bytes = bytes; }
50e91f5b-a39a-44b0-a56a-3f9335200249
9
@Override public String getStat(String code) { if(CMLib.coffeeMaker().getGenMobCodeNum(code)>=0) return CMLib.coffeeMaker().getGenMobStat(this,code); switch(getCodeNum(code)) { case 0: return ""+getWhatIsSoldMask(); case 1: return prejudiceFactors(); case 2: return bankChain(); case 3: return ""+getCoinInterest(); case 4: return ""+getItemInterest(); case 5: return ignoreMask(); case 6: return ""+getLoanInterest(); case 7: return CMParms.toListString(itemPricingAdjustments()); default: return CMProps.getStatCodeExtensionValue(getStatCodes(), xtraValues, code); } }
b0eeb7a6-8860-4b3d-9458-4d1ceef9f2e3
3
public boolean isDead() { if (age > esperancevie) return true; else if (age <= 5 && (loterie.nextInt(25) + 1) == 1) return true; else return false; }
cdd590e5-68a1-47bc-90fd-982963a32a90
9
private boolean r_mark_suffix_with_optional_n_consonant() { int v_1; int v_2; int v_3; int v_4; int v_5; int v_6; int v_7; // (, line 132 // or, line 134 lab0: do { v_1 = limit - cursor; lab1: do { // (, line 133 // (, line 133 // test, line 133 v_2 = limit - cursor; // literal, line 133 if (!(eq_s_b(1, "n"))) { break lab1; } cursor = limit - v_2; // next, line 133 if (cursor <= limit_backward) { break lab1; } cursor--; // (, line 133 // test, line 133 v_3 = limit - cursor; if (!(in_grouping_b(g_vowel, 97, 305))) { break lab1; } cursor = limit - v_3; break lab0; } while (false); cursor = limit - v_1; // (, line 135 // (, line 135 // not, line 135 { v_4 = limit - cursor; lab2: do { // (, line 135 // test, line 135 v_5 = limit - cursor; // literal, line 135 if (!(eq_s_b(1, "n"))) { break lab2; } cursor = limit - v_5; return false; } while (false); cursor = limit - v_4; } // test, line 135 v_6 = limit - cursor; // (, line 135 // next, line 135 if (cursor <= limit_backward) { return false; } cursor--; // (, line 135 // test, line 135 v_7 = limit - cursor; if (!(in_grouping_b(g_vowel, 97, 305))) { return false; } cursor = limit - v_7; cursor = limit - v_6; } while (false); return true; }