method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
912e3a48-ed5d-4eac-a22d-0543aac938e6
9
@Override public void run() { super.run(); try{ recieveData: while(running){ if(!fromServer.ready()){ sleep(100); continue; } String line = fromServer.readLine(); if(line.isEmpty()){ continue recieveData; } parent.updateJustPinged(); String[] lines = line.split("\\s+"); try{ parseCommand(lines); parseServerStatus(lines); }catch(ArrayIndexOutOfBoundsException e){ }catch(NullPointerException e){ } } parent.close(ServerState.DROPPED); }catch(IllegalStateException e){ System.out.println("Closing connection input."); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { } try { toServer.close(); fromServer.close(); } catch (IOException e) { e.printStackTrace(); } System.out.println("closed reciever"); }
d87f7ecb-c8b0-4e76-ae95-3148a00f42c2
8
protected void printTopBeta(int k, String topBetaFile) { System.out.println("TopWord FilePath:" + topBetaFile); Arrays.fill(m_sstat, 0); for (_Doc d : m_trainSet) { for (int i = 0; i < number_of_topics; i++) m_sstat[i] += m_logSpace ? Math.exp(d.m_topics[i]) : d.m_topics[i]; } Utils.L1Normalization(m_sstat); try { PrintWriter topWordWriter = new PrintWriter(new File(topBetaFile)); for (int i = 0; i < m_beta.length; i++) { MyPriorityQueue<_RankItem> fVector = new MyPriorityQueue<_RankItem>( k); for (int j = 0; j < vocabulary_size; j++) fVector.add(new _RankItem(m_corpus.getFeature(j), m_beta[i][j])); topWordWriter.format("Topic %d(%.5f):\t", i, m_sstat[i]); for (_RankItem it : fVector) topWordWriter.format("%s(%.5f)\t", it.m_name, m_logSpace ? Math.exp(it.m_value) : it.m_value); topWordWriter.write("\n"); } topWordWriter.close(); } catch (Exception ex) { System.err.print("File Not Found"); } }
3eaf83be-6028-4a23-8b58-c195186e8661
4
public static TypeAdapterFactory newEnumTypeHierarchyFactory() { return new TypeAdapterFactory() { @SuppressWarnings({"rawtypes", "unchecked"}) public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) { Class<? super T> rawType = typeToken.getRawType(); if (!Enum.class.isAssignableFrom(rawType) || rawType == Enum.class) { return null; } if (!rawType.isEnum()) { rawType = rawType.getSuperclass(); // handle anonymous subclasses } return (TypeAdapter<T>) new EnumTypeAdapter(rawType); } }; }
95161cce-7c89-464e-862c-ac999b534094
9
private boolean flush(DatagramSessionImpl session) throws IOException { // Clear OP_WRITE SelectionKey key = session.getSelectionKey(); if (key == null) { scheduleFlush(session); return false; } if (!key.isValid()) { return false; } key.interestOps(key.interestOps() & (~SelectionKey.OP_WRITE)); DatagramChannel ch = session.getChannel(); Queue<WriteRequest> writeRequestQueue = session.getWriteRequestQueue(); int writtenBytes = 0; int maxWrittenBytes = ((DatagramSessionConfig) session.getConfig()).getSendBufferSize() << 1; try { for (;;) { WriteRequest req = writeRequestQueue.peek(); if (req == null) break; ByteBuffer buf = (ByteBuffer) req.getMessage(); if (buf.remaining() == 0) { // pop and fire event writeRequestQueue.poll(); buf.reset(); if (!buf.hasRemaining()) { session.increaseWrittenMessages(); } session.getFilterChain().fireMessageSent(session, req); continue; } int localWrittenBytes = ch.write(buf.buf()); writtenBytes += localWrittenBytes; if (localWrittenBytes == 0 || writtenBytes >= maxWrittenBytes) { // Kernel buffer is full or wrote too much key.interestOps(key.interestOps() | SelectionKey.OP_WRITE); return false; } else { key.interestOps(key.interestOps() & (~SelectionKey.OP_WRITE)); // pop and fire event writeRequestQueue.poll(); buf.reset(); if (!buf.hasRemaining()) { session.increaseWrittenMessages(); } session.getFilterChain().fireMessageSent(session, req); } } } finally { session.increaseWrittenBytes(writtenBytes); } return true; }
c3b69f29-e3af-4ea4-b2c9-6d792a3a55c4
0
public boolean isExecute() { return execute; }
3c804954-3c51-4548-a307-27e69e54599b
3
public int smaLookback( int optInTimePeriod ) { if( (int)optInTimePeriod == ( Integer.MIN_VALUE ) ) optInTimePeriod = 30; else if( ((int)optInTimePeriod < 2) || ((int)optInTimePeriod > 100000) ) return -1; return optInTimePeriod - 1; }
c6b9b5c6-5bae-4c69-ae80-121a577361c7
6
public static void muteAll(){ // Used for the loops int i; // Used so that the methods associated with a video player can be accessed. VideoPlayer currentVideoPlayer; // Used so that the methods associated with a Audio player can be accessed. AudioPlayer currentAudioPlayer; // Used so that the methods associated with a midi player can be accessed. MidiPlayer currentMidiPlayer; // Tests whether there are any entities to displayed on the slide. if (entityPlayers != null) { for(i =0;i <entityPlayers.size(); i++) { // test whether the players are active. if (entityPlayers.get(i).getIsActive()) { if (entityPlayers.get(i) instanceof VideoPlayer) { // Mute method called currentVideoPlayer = (VideoPlayer) entityPlayers.get(i); currentVideoPlayer.muteMedia(); } if (entityPlayers.get(i) instanceof AudioPlayer) { // Mute method called currentAudioPlayer = (AudioPlayer) entityPlayers.get(i); currentAudioPlayer.muteMedia(); } if (entityPlayers.get(i) instanceof MidiPlayer) { // Mute method called currentMidiPlayer = (MidiPlayer) entityPlayers.get(i); currentMidiPlayer.muteMedia(); } } } } }
ff398f34-4cc2-4db4-84e1-4be0f9c08ba2
3
public void addNote(Note note) { // Log.v(TAG, note.text); if (note == null) { notes = new ArrayList<Note>(); } if (alerts == null) { alerts = new ArrayList<Alerts>(); } if (!notes.contains(note)) { notes.add(note); } }
510d653a-52da-4af7-a690-e8fe28cf2c67
1
static int ternary(int i) { return i < 10 ? i * 100 : i * 10; }
5cee5c8c-518d-4ef9-8007-49ca9fed6752
2
public boolean instanceOf(Object obj, String className) throws InterpreterException { Class clazz; try { clazz = Class.forName(className); } catch (ClassNotFoundException ex) { throw new InterpreterException("Class " + ex.getMessage() + " not found"); } return obj != null && !clazz.isInstance(obj); }
f0980796-b2b5-43e3-9c0e-ac262c54d98e
3
private void storeAttribute(Attr attribute) { // examine the attributes in namespace xmlns if (attribute.getNamespaceURI() != null && attribute.getNamespaceURI().equals(XMLConstants.XMLNS_ATTRIBUTE_NS_URI)) { // Default namespace xmlns="uri goes here" if (attribute.getNodeName().equals(XMLConstants.XMLNS_ATTRIBUTE)) { putInCache(DEFAULT_NS, attribute.getNodeValue()); } else { // The defined prefixes are stored here putInCache(attribute.getLocalName(), attribute.getNodeValue()); } } }
4c07db94-19d6-44fd-80ad-5fd5ec394845
1
public final JSONArray optJSONArray(int index) { Object o = opt(index); return o instanceof JSONArray ? (JSONArray)o : null; }
a0474e77-a968-4f7c-a8a2-5079caa0b7b3
2
private GekozenAntwoord kiesOnderdeel(final Onderdeel optie) { final GekozenAntwoord gk = spel.kiesOnderdeel(optie); final DefaultComboBoxModel onderdelenComboBoxModel = new DefaultComboBoxModel(); for (Onderdeel comboOptie : onderdelen) onderdelenComboBoxModel.addElement(comboOptie); onderdelenComboBoxModel.setSelectedItem(gk.getGekozenOnderdeel()); onderdelenComboBoxModel.addListDataListener(new ListDataListener() { @Override public void contentsChanged(ListDataEvent e) { Onderdeel van = gk.getGekozenOnderdeel(); Onderdeel naar = (Onderdeel) onderdelenComboBoxModel.getSelectedItem(); spel.wijzigAntwoord(van, naar); } @Override public void intervalAdded(ListDataEvent e) {} @Override public void intervalRemoved(ListDataEvent e) {} }); views.panels.GekozenAntwoord gkView = new views.panels.GekozenAntwoord(gk, onderdelenComboBoxModel); gekozenAntwoordenPanel.add(gkView, "cell " + currentCell + " 0,grow"); gekozenAntwoorden.add(gkView); gk.addObserver(gkView); currentCell++; gekozenAntwoordenPanel.getParent().validate(); try { volgendeOnderdeel(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return gk; }
9ec6a4b3-a2d1-41e4-a02e-e9e8ce130c6b
0
public void setPassword(String password) { this.password = password; }
4c67a195-748e-4293-b853-f3efc8c7ba3a
2
public String getColumnName(int columnIndex) { String colName = new String(); if (columnIndex>=0&&columnIndex<=(title.size())) colName=(String)title.get(columnIndex); return colName; }
1e3d47b0-3843-4d8a-9f88-2bdf782cb123
8
@Override public void readConstructorParams(DataInput in) throws IOException { super.readConstructorParams(in); String fontName = in.readUTF(); int style = in.readInt(); int size = in.readInt(); font = new Font(fontName, style, size); tesselationTolerance = in.readDouble(); GeneralPath shape = null; int segType = in.readInt(); while (segType != Integer.MIN_VALUE) { if (shape == null) shape = new GeneralPath(); if (segType == PathIterator.SEG_MOVETO) { shape.moveTo(in.readFloat(), in.readFloat()); } else if (segType == PathIterator.SEG_LINETO) { shape.lineTo(in.readFloat(), in.readFloat()); } else if (segType == PathIterator.SEG_QUADTO) { shape.quadTo(in.readFloat(), in.readFloat(), in.readFloat(), in .readFloat()); } else if (segType == PathIterator.SEG_CUBICTO) { shape.curveTo(in.readFloat(), in.readFloat(), in.readFloat(), in.readFloat(), in.readFloat(), in.readFloat()); } else if (segType == PathIterator.SEG_CLOSE) { shape.closePath(); } segType = in.readInt(); } if (shape != null) extrudePath = new FontExtrusion(shape, in.readDouble()); else extrudePath = null; }
c3b32770-32c9-4850-a4b8-3f3292ac50ad
4
@Override public void execute() { if (itemscroll == 0) seqEflButton(A); else if (itemscroll == 1) seqEflButton(A | DOWN); else if (itemscroll == 2) seqEflScrollFastAF(itemscroll); else seqEflScrollFastA(itemscroll); if (scroll == 0) seqEflButton(A, PRESSED); else seqEflScrollA(scroll, PressMetric.DOWN); seq(new EflSkipTextsSegment(1)); // that will be seq(new EflSkipTextsSegment(1, true)); //ok? seq(new EflSkipTextsSegment(1, endWithA)); // thank you }
3f84ddf0-4875-431e-88b9-a24c32353963
3
public boolean setValue(int index, Expression value) { if (index < 0 || index > subExpressions.length || subExpressions[index] != empty) return false; value.setType(argType); setType(Type.tSuperType(Type.tArray(value.getType()))); subExpressions[index] = value; value.parent = this; value.makeInitializer(argType); return true; }
776bbca2-9246-4375-a80f-b9b988ed1438
7
public static boolean insertWork(Work work){ try{ Connection con = DBManager.getConnection(); if(con==null) return false; StringBuilder sql = new StringBuilder("insert into work_table ("); sql.append(" work_dlsite_id"); sql.append(",circle_id"); sql.append(",work_name"); sql.append(",price"); sql.append(",dl"); sql.append(",url"); sql.append(",exp_long"); sql.append(",exp_short"); sql.append(",img_thumb"); sql.append(",img_main"); sql.append(",img_sample1"); sql.append(",img_sample2"); sql.append(",img_sample3"); sql.append(",day"); sql.append(",adult"); sql.append(",upload"); sql.append(") values ("); sql.append(" ?"); sql.append(",?"); sql.append(",?"); sql.append(",?"); sql.append(",?"); sql.append(",?"); sql.append(",?"); sql.append(",?"); sql.append(",?"); sql.append(",?"); sql.append(",?"); sql.append(",?"); sql.append(",?"); sql.append(",?"); sql.append(",?"); sql.append(",NOW()"); sql.append(");"); PreparedStatement smt = con.prepareStatement(sql.toString()); //カラムカウンタ int i = 1; //DLSiteID smt.setString(i++, work.getDlSiteId()); //サークルID smt.setInt(i++, work.getCircle().getId()); //作品名 smt.setString(i++, work.getName()); //価格 smt.setInt(i++, work.getPrice()); //ダウンロード数 smt.setInt(i++, work.getDl()[0].getDl()); //作品URL smt.setString(i++, work.getUrl()); //紹介文 長 smt.setString(i++, work.getExp_long()); //紹介文 短 smt.setString(i++, work.getExp_short()); //サムネイル画像 smt.setString(i++, work.getImages().getThumb()); //メイン画像 smt.setString(i++, work.getImages().getMain()); //サンプル画像 for(int j=0; j<3; j++){ //サンプル画像があれば挿入 if(work.getImages()!=null && work.getImages().getSamples()!=null && work.getImages().getSamples().length > j){ smt.setString(i++, work.getImages().getSamples()[j]); //なければnull挿入 }else{ smt.setString(i++, null); } } //販売開始日 smt.setDate(i++, work.getDate()); //アダルトフラグ smt.setBoolean(i++, work.getAdult()); //クエリ実行 int row = smt.executeUpdate(); con.close(); if(row==0) return false; }catch(Exception e){ e.printStackTrace(); return false; } return true; }
4266cace-2602-4963-8f0e-1be48e246260
5
@RequestMapping(method = RequestMethod.GET) protected ModelAndView handleHomePageRequest( HttpServletRequest request, HttpServletResponse response) { HttpSession currentSession = request.getSession(); User verifiedUserInSession = (User) currentSession.getAttribute( GraduatesSessionAttributes.ATTRI_USER); if (verifiedUserInSession != null) { homeModelAndView.addObject(ATTRI_USER_BEAN, verifiedUserInSession); return homeModelAndView; } String username = getCookieValueByName(request, COOKIE_USERNAME); String password = getCookieValueByName(request, COOKIE_PASSWORD); boolean cookieIncomplete = username == null || password == null; if (cookieIncomplete) { return registerModelAndView; } try { User verifiedUser = userAccountService.verify(username, password); boolean verified = (verifiedUser != null); if (!verified) { removeCookieByName(response, COOKIE_USERNAME); removeCookieByName(response, COOKIE_PASSWORD); return loginModelAndView; } long userId = verifiedUser.getId(); homeModelAndView.addObject(ATTRI_USER_BEAN, verifiedUser); addWordsBean(homeModelAndView, userId); return homeModelAndView; } catch (DataAccessException ex) { logger.log(Level.SEVERE, ex.getMessage(), ex); return homeModelAndView; } }
ef56bdce-e36c-47a3-8e53-0f8536abb4d7
9
public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); int T = sc.nextInt(); int M = sc.nextInt(); List<Submission> sub = new ArrayList<Submission>(); boolean[][] accepted = new boolean[T][N]; for (int i = 0; i < M; i++) { int time = sc.nextInt(); int team = sc.nextInt(); String problem = sc.next(); boolean verdict = sc.next().equals("Yes") ? true : false; if (!accepted[team - 1][problem.charAt(0) - 'A'] && verdict) { sub.add(new Submission(time, team, problem, verdict)); accepted[team - 1][problem.charAt(0) - 'A'] = true; } } String[] result = new String[N]; Arrays.fill(result, ""); for (int i = sub.size() - 1; i >= 0; i--) { Submission s = sub.get(i); if (s.verdict && result[s.problem.charAt(0) - 'A'].equals("")) { result[s.problem.charAt(0) - 'A'] = s.time + " " + s.team; } } for (int i = 0; i < N; i++) { System.out.print((char) ('A' + i) + " "); if (result[i].equals("")) { System.out.println("- -"); } else { System.out.println(result[i]); } } }
ccf3c6be-53b1-481a-a3f2-b5f2dd49e649
2
public static void main(String[] args) { Field field = new Field(); field.print(); int y = 0; for (String s: field.getWords()){ if (Request.validate(s)) { System.out.println(s); y++; } } System.out.println(y + "words totally"); }
d3d9dda1-cc47-4a0b-9169-1b4be6a936e0
2
private void populateEntity() { enemys = new ArrayList<Enemy>(); entities = new ArrayList<EntitySpecial>(); Slugger s; Crawler s2; Point[] points = new Point[] { new Point(860, 200), new Point(1525, 200), new Point(1680, 200), new Point(1800, 200) }; Point[] points2 = new Point[] { new Point(960, 200) }; for (int i = 0; i < points.length; i++) { s = new Slugger(tileMap); s.setPosition(points[i].x, points[i].y); enemys.add(s); } for (int i = 0; i < points2.length; i++) { s2 = new Crawler(tileMap); s2.setPosition(points2[i].x, points2[i].y); enemys.add(s2); } }
8d53ffbb-a6ec-4f0c-9858-6cf3f1be2a09
4
public void run() { System.out.println("Welcome to Server side"); ServerSocket servers = null; Socket fromclient = null; // create server socket try { servers = new ServerSocket(4444); } catch (IOException e) { System.out.println("Couldn't listen to port 4444"); System.exit(-1); } try { while (true) { fromclient = servers.accept(); Client clientThread = new Client(fromclient); Thread t = new Thread(clientThread); t.start(); System.out.println("Client connected"); } } catch (IOException e) { System.out.println("Can't accept"); System.exit(-1); } try { servers.close(); } catch (IOException ex) { System.out.println("Can't close socket"); System.exit(-1); } // Тут мы обслуживаем клиента }
923dfa7f-9aa9-4952-b955-8cfcba37f4f5
2
public static Question getNextQuestion() { if (questions == null || ++position >= questions.size()) { Runnable getQuestionRunnable = new Runnable() { public void run() { position = 0; questions = DatabaseManager.getRandomQuestions(50, Type.BRAIN); //todo remove this hardcode loadingDialog.dispose(); } }; Thread getQuestionThread = new Thread(getQuestionRunnable); getQuestionThread.start(); loadingDialog.showDialog(); } return questions.get(position); }
84427c66-a815-412b-b89c-b3f3c4e5adf9
7
public Expr evaluate(IEvaluationContext context, Expr[] args) throws ExprException { assertArgCount(args, 3); Expr ea = evalArg(context, args[0]); if (!isNumber(ea)) return ExprError.VALUE; double alpha = asDouble(context, ea, true); if (alpha <= 0 || alpha >= 1) return ExprError.NUM; Expr es = evalArg(context, args[1]); if (!isNumber(es)) return ExprError.VALUE; double stdev = asDouble(context, es, true); if (stdev <= 0) return ExprError.NUM; Expr esi = evalArg(context, args[2]); if (!isNumber(esi)) return ExprError.VALUE; int size = asInteger(context, esi, true); if (size < 1) return ExprError.NUM; return new ExprDouble(Statistics.confidence(alpha, stdev, size)); }
da3c9ca1-4cc3-4b23-9355-8bf3076b0f63
0
public void setName(String name) { this.name = name; }
c4d09526-552d-4627-a37e-fceea4d287d9
7
public static void main(String [] args) { try { if (args.length < 1) { System.err.println("Usage : weka.gui.visualize.Plot2D " +"<dataset> [<dataset> <dataset>...]"); System.exit(1); } final javax.swing.JFrame jf = new javax.swing.JFrame("Weka Explorer: Visualize"); jf.setSize(500,400); jf.getContentPane().setLayout(new BorderLayout()); final Plot2D p2 = new Plot2D(); jf.getContentPane().add(p2, BorderLayout.CENTER); jf.addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent e) { jf.dispose(); System.exit(0); } }); p2.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { if ((e.getModifiers() & InputEvent.BUTTON1_MASK) == InputEvent.BUTTON1_MASK) { p2.searchPoints(e.getX(), e.getY(), false); } else { p2.searchPoints(e.getX(), e.getY(), true); } } }); jf.setVisible(true); if (args.length >= 1) { for (int j = 0; j < args.length; j++) { System.err.println("Loading instances from " + args[j]); java.io.Reader r = new java.io.BufferedReader( new java.io.FileReader(args[j])); Instances i = new Instances(r); i.setClassIndex(i.numAttributes()-1); PlotData2D pd1 = new PlotData2D(i); if (j == 0) { pd1.setPlotName("Master plot"); p2.setMasterPlot(pd1); p2.setXindex(2); p2.setYindex(3); p2.setCindex(i.classIndex()); } else { pd1.setPlotName("Plot "+(j+1)); pd1.m_useCustomColour = true; pd1.m_customColour = (j % 2 == 0) ? Color.red : Color.blue; p2.addPlot(pd1); } } } } catch (Exception ex) { ex.printStackTrace(); System.err.println(ex.getMessage()); } }
24eee941-21eb-4b26-9cbe-5ed1e12ee269
8
private void dfs(char[][] grid, int i, int j, int count) { if (i - 1 >= 0) { if (grid[i - 1][j] == '1') { grid[i - 1][j] = (char) ('0' + count); dfs(grid, i - 1, j, count); } } if (j - 1 >= 0) { if (grid[i][j - 1] == '1') { grid[i][j - 1] = (char) ('0' + count); dfs(grid, i, j - 1, count); } } if (i + 1 < grid.length) { if (grid[i + 1][j] == '1') { grid[i + 1][j] = (char) ('0' + count); dfs(grid, i + 1, j, count); } } if (j + 1 < grid[0].length) { if (grid[i][j + 1] == '1') { grid[i][j + 1] = (char) ('0' + count); dfs(grid, i, j + 1, count); } } }
f4b6a1f6-d3bd-45ea-a8bd-1e6068097c63
8
private Point getRealPosition(IReadableMolecule anchorMolecule, RelativePosition position) { // Precondition assertTrue("Unknown molecule.", knowsMoleculePosition(anchorMolecule)); // Get the anchor's position. final Point POSITION_OF_ANCHOR = mutableWorld.getPositionOfMolecule(anchorMolecule); // Get the offset from the position. int xOffset = 0, yOffset = 0; switch (position) { case North: yOffset = -1; break; case South: yOffset = 1; break; case East: xOffset = 1; break; case West: xOffset = -1; break; case NorthWest: yOffset = -1; xOffset = -1; break; case NorthEast: yOffset = -1; xOffset = 1; break; case SouthWest: yOffset = 1; xOffset = -1; break; case SouthEast: yOffset = 1; xOffset = 1; break; default: fail("Unexpected value ("+position+")"); break; } // Return the relative position as a real point in the world. return new Point(POSITION_OF_ANCHOR.x + xOffset, POSITION_OF_ANCHOR.y + yOffset); }
36f81a32-95ef-4ac1-bd89-d19f53543e20
5
@Override public Intersection getIntersection(Ray ray) { Vector distance = Vector.minus(this.position, ray.origin); double b = Vector.dot(ray.direction, distance); double d = b * b - Vector.dot(distance, distance) + this.radius * this.radius; if (d < 0.0d) return null; // calculate both solutions double t = 0; double t0 = b - Math.sqrt(d); double t1 = b + Math.sqrt(d); // find smallest positive t if (t0 > 0) t = t0; if (t1 > 0 && t1 < t0) t = t1; // return intersection if (t > 0) { Vector position = ray.solve(t); Vector normal = Vector.minus(position, this.position).normalize(); return new Intersection(this, t, position, normal); } return null; }
c43a0c63-c699-480e-886d-70aa10ca4651
0
public String getSampleInput() { return this.sampleInput; }
6dc49e14-1b88-4afc-a48d-11a1ced51db6
2
private String join(Collection s, String delimiter) { StringBuilder buffer = new StringBuilder(); Iterator iter = s.iterator(); while (iter.hasNext()) { buffer.append(iter.next()); if (iter.hasNext()) { buffer.append(delimiter); } } return buffer.toString(); }
5ccfa9b6-5b09-4add-a7a7-3567597274e6
0
public OutlineButton(OutlinerCellRendererImpl renderer) { this.renderer = renderer; setVerticalAlignment(SwingConstants.TOP); setOpaque(true); setVisible(false); }
2e923c46-30b3-40ed-a6c1-2611ef0023c7
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(ClientRepUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ClientRepUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ClientRepUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ClientRepUI.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 ClientRepUI().setVisible(true); } }); }
ed7934d6-b8db-43ef-92b4-0ecf5d375dbe
7
public static void main(String[] args) { if (args.length != 3) { System.err.println("Usage: AssociationsFinder <fileName> <min_support> <min_confidence>"); System.exit(1); } String fileName = args[0]; Double min_support = 0.0; Double min_confidence = 0.0; try { min_support = Double.parseDouble(args[1]); min_confidence = Double.parseDouble(args[2]); } catch (Exception e) { System.err.println("Error parsing values of min_support or min_confidence. Please check values."); System.exit(1); } if (min_support <= 0.0 || min_support > 1) { System.err.println("Min Support value should be in (0,1]"); System.exit(1); } if (min_confidence <= 0.0 || min_confidence > 1) { System.err.println("Min confidence value should be in (0,1]"); System.exit(1); } ItemsetGenerator generator; try { generator = new ItemsetGenerator(fileName, min_support, min_confidence); generator.generateAssociations(); System.out.println("output.txt contains detailed results"); } catch (IOException e) { System.err.println("Can't create output file. Error Message: " + e.getMessage()); System.exit(1); } }
3eb623d0-f76a-44ae-aa30-da7decd375fd
7
public List<FTPFile> parse(List<String> serverLines, String parentPath) { List<FTPFile> files = new ArrayList<FTPFile>(serverLines.size()); for (String line : serverLines) { FTPFile file = null; try { log.debug("Trying to parse line: " + line); file = parser.parse(line, parentPath); }catch (ParseException pe) { // Expected parser couldn't parse trying other parsers try { log.warn("Previous file parser couldn't parse listing. Trying a UNIX file parser"); parser = new UnixFileParser(locale); file = parser.parse(line, parentPath); }catch (ParseException pe2) { try { log.warn("Previous file parser couldn't parse listing. Trying a EPLF file parser"); parser = new EPLFFileParser(); file = parser.parse(line, parentPath); }catch (ParseException pe5) { try { log.warn("Previous file parser couldn't parse listing. Trying a netware file parser"); parser = new NetwareFileParser(locale); file = parser.parse(line, parentPath); }catch (ParseException pe3) { log.warn("Last chance!!! calling LastChanceFileParser"); parser = new LastChanceFileParser(locale); try { file = parser.parse(line, parentPath); }catch (ParseException pe4) { log.fatal("Couldn't parse the LIST reply"); } } } } } if (file != null) files.add(file); } return files; }
cd383691-fd67-4a76-927c-74d38d963693
2
public void wallHit(int a){ if(a==1){ directionX = directionX*-1; } if(a==2){ directionY = directionY*-1; } }
d2c1dcbc-aeca-4ab2-9e16-54abb3935dbd
2
public static Sprite get(String ref) { if(sprites.containsKey(ref)) { return sprites.get(ref); } if(ref != null) { sprites.put(ref, new Sprite(ref)); } return sprites.get(ref); }
37520256-4385-4e9f-a033-6baed7100194
2
private double search() { double l=mu-sigma*2; double r=mu+sigma*2; while (l+0.1<r){ double t1=(r-l)/3+l; double t2=2*(r-l)/3+l; if(f(t1) < f(t2)) l=t1; else r=t2; } return (l+r)/2; }
51e89c59-7438-45ef-b4c9-470629626578
8
@Override public void setStat(String code, String val) { if(CMLib.coffeeMaker().getGenItemCodeNum(code)>=0) CMLib.coffeeMaker().setGenItemStat(this,code,val); else switch(getCodeNum(code)) { case 0: setPowerCapacity(CMath.s_parseLongExpression(val)); break; case 1: activate(CMath.s_bool(val)); break; case 2: setPowerRemaining(CMath.s_parseLongExpression(val)); break; case 3: setManufacturerName(val); break; case 4: setClothingLayer((short) CMath.s_parseIntExpression(val)); break; case 5: setLayerAttributes((short) CMath.s_parseListLongExpression(Armor.LAYERMASK_DESCS, val)); break; case 6: setTechLevel(CMath.s_parseIntExpression(val)); break; default: CMProps.setStatCodeExtensionValue(getStatCodes(), xtraValues, code, val); break; } }
e4d0a04c-a22e-4060-a053-3ebc8b98a1b7
2
public Tile(Point location, Room containingRoom){ if (location == null || containingRoom == null){ throw new IllegalArgumentException("A tile must have a location and a containing room"); } edges = new HashMap<Direction, Edge>(); inventory = new Inventory(); //start empty, avoids null pointers character = null; //no character this.location = location; this.containingRoom = containingRoom; }
655e4cd9-8a17-4d79-aae6-7a25a3ab59e9
0
@Basic @Column(name = "tipo") public String getTipo() { return tipo; }
1cffa5b2-4e17-46a7-9f86-710860bee199
7
private void search(String fileName) { File file = new java.io.File(fileName + ".html.txt"); File fileHistory = new java.io.File(fileName + ".history.txt"); FileWriter fw = null; FileWriter fwHistory = null; try { fw = new FileWriter(file); fwHistory = new FileWriter(fileHistory); fw.write("開始時間: " + Calendar.getInstance().getTime() + "\r\n"); fwHistory.write("開始時間: " + Calendar.getInstance().getTime() + "\r\n"); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } String url = ""; lastTime = Calendar.getInstance().getTimeInMillis(); while(!this.spiderEngine.getUnsearchList().isEmpty()){ url = this.spiderEngine.peekUnsearchQueue().getUrl(); try { if (!this.spiderEngine.isSearched(url)) { WebPage srb = processHtml(url); fw.write(srb.getText().toString()); fwHistory.write(url + "\r\n"); srb = null; url = null; count++; if(count % 50 == 0){ System.gc(); System.out.println("GC:"+count); } if (count % 100 == 0) { fwHistory.write("需解析的鏈結列表: " + this.spiderEngine.getUnsearchList().size() + "\r\n"); fwHistory.write("已經被搜索站點列表: " + this.spiderEngine.getSearchedSites().size() + "\r\n"); long crossTime = Calendar.getInstance().getTimeInMillis() - lastTime; fwHistory.write("此回搜尋用了: " + crossTime + "毫秒("+ getRightNowTimeStr("-", ":", "_") + ")\r\n"); lastTime = Calendar.getInstance().getTimeInMillis(); // //System.gc(); // System.out.println("需解析的鏈結列表: " + this.spiderEngine.getUnsearchList().size()); System.out.println("已經被搜索站點列表: " + this.spiderEngine.getSearchedSites().size()); System.out.println("此回搜尋用了: " + crossTime); System.out.println(count); } if (count % 1000 == 0) { count = 0; fw.close(); fw = null; file = null; file = new java.io.File(createFileName() + ".html.txt"); fw = new FileWriter(file); System.out.println(count); } } } catch (Exception ex) { } } }
21eca6ea-dd0e-4ebc-94f3-9ecd86074960
9
@Override public boolean playerSignIn(String pUsername, String pPassword, String pIPAddress) { if((pUsername.charAt(0) > 'Z' && pUsername.charAt(0) < 'a') || pUsername.charAt(0) < 'A' || pUsername.charAt(0) > 'z') { aLog.info("Error Player Sign in : Username cannot start with " + pUsername.charAt(0)); return false; } Account tmpAccount = getAccount(pUsername); if(tmpAccount == null) { aLog.info("Error Player Sign in : Username Was Not Found"); tmpAccount = null; return false; } if(!tmpAccount.getPassword().equals(pPassword)) { aLog.info("Error Player Sign in : Incorrect Password"); tmpAccount = null; return false; } if(!validate(pIPAddress)) { aLog.info("Error Player Sign in : Invalid IP-address"); tmpAccount = null; return false; } if(!tmpAccount.getIPAddress().equals(pIPAddress)) { aLog.info("Error Player Sign in : Nonmatching IP-address"); tmpAccount = null; return false; } if(!tmpAccount.isOnline()) { tmpAccount.setOnline(true); tmpAccount = null; aLog.info("Player Sign in : Player " + pUsername + " Is Now Online"); return true; } else { aLog.info("Error Player Sign in : Player " + pUsername + " Is Already Online"); tmpAccount = null; return false; } }
e4052fec-a2c8-4df9-a581-e9ea3a5d4ea4
2
public void visitJumpInsn(final int opcode, final Label label) { if (mv != null) { mv.visitJumpInsn(opcode, label); } execute(opcode, 0, null); if (opcode == Opcodes.GOTO) { this.locals = null; this.stack = null; } }
ae52c04b-729a-40aa-ad9c-31c7a65da1f4
3
public void actionOpenFile() { JFileChooser fc = new JFileChooser(); fc.setFileSelectionMode(JFileChooser.FILES_ONLY); fc.setDialogTitle(UIStrings.UI_OPEN_MDFILE_LABEL); fc.addChoosableFileFilter(new FileNameExtensionFilter( "Markdown files (.md, .mmd, .markdown, .txt, .text)", "md", "mmd", "markdown", "txt", "text")); int returnVal = fc.showOpenDialog(Joculus.frame); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); if (file.exists() && file.isFile()) { app_instance.setFile(file.getAbsolutePath()); } } }
a50614e9-3fd7-4fd0-aef5-9790cda036a9
5
private static int readMenuChoice(BufferedReader reader, int max) { int result = 0; while (true) { String choice = null; try { choice = reader.readLine(); } catch (IOException e) { e.printStackTrace(); } try { result = Integer.parseInt(choice); } catch (NumberFormatException ignored) { } if (result >= 1 && result <= max) { break; } System.out.println ("Please enter a number corresponding to one of the items in the menu:"); } return result; }
09638b21-ada8-4ca5-80fb-4c8277aa79ed
1
public static ArrayList<PracticeAchievement> getAllAchievements() { if (allAchievements.isEmpty()) loadAllAchievements(); return allAchievements; }
6b67a758-a14c-4758-a3a9-6905fbf179b8
7
public static HGTypedValue project(HyperGraph hg, HGHandle type, Object value, String [] dimPath, boolean throwExceptionOnNotFound) { Object topvalue = value; for (int j = 0; j < dimPath.length; j++) { HGAtomType tinstance = (HGAtomType)hg.get(type); if (! (tinstance instanceof HGCompositeType)) if (throwExceptionOnNotFound) throw new HGException("Only composite types can be indexed by value parts: " + value + ", during projection of " + formatDimensionPath(dimPath) + " in type " + tinstance); else return null; HGProjection proj = ((HGCompositeType)tinstance).getProjection(dimPath[j]); if (proj == null) if (throwExceptionOnNotFound) throw new HGException("Dimension " + dimPath[j] + " does not exist in type " + tinstance); else return null; if (value == null) throw new IllegalArgumentException("The value " + value + " doesn't have a property at " + Arrays.asList(dimPath)); if (value instanceof HGValueLink) value = ((HGValueLink)value).getValue(); value = proj.project(value); type = proj.getType(); } return new HGTypedValue(value, type); }
868782c8-9445-4243-b2ea-1ebd8e9e6820
0
@Override public void setSector(String sector) { super.setSector(sector); }
07902737-249d-461a-b0a0-bd87074cd340
5
private String[] getHeaderArray(String line) { char[] lineArray = line.toCharArray(); String tmp = ""; String[] split = new String[line.length() + 1/2]; //Cannot be greater int i = 0; // We here build all the strings to go into our array, if we meet a // ' ' we stop and store our accumulated string in the array. for(char c: lineArray){ if (c != ' '){ tmp += c; } else { if(!tmp.equals("")){ split[i++] = tmp; tmp = ""; } } } // We check if there is something left in tmp if(!tmp.equals("")){ split[i++] = tmp; } // Finally we fill the built strings into an array of exact size. String[] res = new String[i]; for(int j = 0; j < i; j++){ res[j] = split[j]; } return res; }
1cd12410-1b34-4b35-a4eb-6e347912a5fc
3
public boolean equalsExpr(final Expr other) { return (other != null) && (other instanceof ArrayRefExpr) && ((ArrayRefExpr) other).array.equalsExpr(array) && ((ArrayRefExpr) other).index.equalsExpr(index); }
bfda53b3-c53e-43e5-9d1e-0b98f632b033
8
private void splitFrames(String hexBuff, String file) throws IOException{ //need to work on salvaging partial frames due to buffer misalignment //and syncwords in the data String[] frames; frames = hexBuff.split(syncWord); for(int frame_i = 0; frame_i < frames.length; frame_i++){ //make sure we have something to work with if(frames[frame_i].length() == 0){continue;} //add sync word back into the frame frames[frame_i] = syncWord + frames[frame_i]; //find any extra or shortage in frame length //Multiply by 2 because hex format gives 1 char per nybble int diff = frames[frame_i].length() - (frameLength * 2); //Make sure the frame length is correct if(diff == 0){ processFrame(frames[frame_i], file); }else if(diff < 0){ //frame is too short //Try to build a full length frame from adjacent pieces String tempFrame = frames[frame_i]; int frame_j = frame_i; while( ((frame_j + 1) < frames.length) && (tempFrame.length() < (frameLength *2)) ){ frame_j++; tempFrame = tempFrame + syncWord + frames[frame_j]; } if(tempFrame.length() == (frameLength * 2)){ frame_i = frame_j; processFrame(tempFrame, file); }else{ System.out.println("Short Frame in file " + file + "."); } }else if(diff > 0){//frame is too long //Long frames wont be saved so move on System.out.println("Long Frame in file " + file + "."); } } }
b909e597-de08-41a7-a7f6-51d5e59b1fd3
1
public static void main(String[] args) throws ParseException, ClassNotFoundException { Connection connect = null; PreparedStatement preparedStatement = null; String t = "17:04:26.636"; System.out.println(t); DateFormat format = new SimpleDateFormat("HH:mm:ss.SSS"); Date date = format.parse(t); System.out.println(date.getTime()); Date datse = new Date(date.getTime()); DateFormat formatter = new SimpleDateFormat("HH:mm:ss.SSS"); String dateFormatted = formatter.format(datse); System.out.println(dateFormatted); System.out.println(System.nanoTime()); try { // this will load the MySQL driver, each DB has its own driver Class.forName("com.mysql.jdbc.Driver"); // setup the connection with the DB. connect = DriverManager.getConnection("jdbc:mysql://localhost/cdr_data?user=root&password=root"); // preparedStatements can use variables and are more efficient preparedStatement = connect.prepareStatement("insert into test1 (ID,t) values (?,TIME_FORMAT(?, '%H:%i:%s.%f'));"); preparedStatement.setInt(1, 10); preparedStatement.setString(2, "17:04:26.29"); preparedStatement.executeUpdate(); } catch (SQLException e) { Logger.getLogger(ConcurrentDataInsertTest.class.getName()).log(Level.SEVERE, null, e); } }
70439f81-b18c-4998-b65d-02335261e482
3
public void rebuild(){ topPanel.removeAll(); bottomPanel.removeAll(); topTabs = new ArrayList<TabButton>(); bottomTabs = new ArrayList<TabButton>(); for(DataTabButton tabData : tabsDatabase){ TabButton tab = new TabButton(tabData); if(tabData.orientation == 0){ topTabs.add(tab); } else if(tabData.orientation == 1){ bottomTabs.add(tab); } } }
a7bfdb35-e395-4034-aa98-2a62cf66f428
0
@Override public void execute(VirtualMachine vm) { DebuggerVirtualMachine dvm = (DebuggerVirtualMachine) vm; dvm.setCurrentLine(lineNumber); }
8febd838-b187-4115-a164-c6bd2ced9052
0
public void save(PermissionBase holder) throws DataSaveFailedException { dataHolder.save(holder); }
078abe3f-7872-4a13-bdde-02908d8544cc
5
@Override public void onChatComplete(Player player, String enteredText, Object... args) throws EssentialsCommandException { RankAction action = (RankAction)args[1]; @SuppressWarnings("unchecked") ArrayList<Player> targetPlayers = (ArrayList<Player>)args[0]; for(Player target: targetPlayers) { // make sure they're still here if(target == null) { continue; } switch(action) { case PROMOTE: promote(player, target, enteredText); break; case DEMOTE: demote(player, target, enteredText); break; case HOTDOG: hotdog(player, target, enteredText); break; } } }
aa0b35bb-e8fd-44bb-b7a9-40fff35cf764
7
@Override public boolean serialize(JsonSerializer serializer, JsonFragmentBuilder builder, Object value) { boolean result; Method toJson=findMethod(value.getClass(), boolean.class, Arrays.asList("toJson"), JsonFragmentBuilder.class); if(toJson != null) { try { result = (Boolean) toJson.invoke(value, builder); } catch (IllegalArgumentException e) { JsonSerializationException e2=serializer.getExceptionPolicy().format(e); if(e2 != null) throw e2; result = false; } catch (IllegalAccessException e) { JsonSerializationException e2=serializer.getExceptionPolicy().format(e); if(e2 != null) throw e2; result = false; } catch (InvocationTargetException e) { JsonSerializationException e2=serializer.getExceptionPolicy().format(e); if(e2 != null) throw e2; result = false; } } else result = false; return result; }
42b1d43a-7770-4fe2-98ac-9cc2c3602333
5
private boolean jj_3R_59() { if (jj_3R_74()) return true; if (jj_scan_token(POINT)) return true; Token xsp; while (true) { xsp = jj_scanpos; if (jj_3_58()) { jj_scanpos = xsp; break; } } if (jj_3R_72()) return true; return false; }
da5de4fa-014c-4f93-b1c8-03b890280d1a
8
@Override protected void respond(Channel channel) throws IOException { ProtocolData received = new ProtocolData(buffer); if (received.getMessage() == ProtocolMessage.CONNECTION_OK) { ps.printf("[Conexão: %s]\n", df.format(new Date())); connectionOK(channel, received); } else if (received.getMessage() == ProtocolMessage.LOGIN_REQUEST) { String userName = received.getHeaderLine(0); ps.printf("[Solicitação de login (%s): %s]\n", userName, df.format(new Date())); loginRequest(channel, received); } else if (received.getMessage() == ProtocolMessage.USERS_REQUEST) { ps.printf("[Solicitação de usuários: %s]\n", df.format(new Date())); usersRequest(channel); } else if (received.getMessage() == ProtocolMessage.CHAT_REQUEST) { String requested = received.getHeaderLine(0); String sender = received.getHeaderLine(1); ps.printf("[Solicitação de bate-papo (%s -> %s): %s]\n", sender, requested, df.format(new Date())); chatRequest(channel, received); } else if (received.getMessage() == ProtocolMessage.CHAT_END) { String userName = received.getHeaderLine(0); ps.printf("[Solicitação de encerramento de bate-papo (%s): %s]\n", userName, df.format(new Date())); chatEnd(channel, received); } else if (received.getMessage() == ProtocolMessage.TRANSFER_REQUEST) { String receiver = received.getHeaderLine(0); String sender = received.getHeaderLine(1); ps.printf("[Solicitação de transferência (%s -> %s): %s]\n", sender, receiver, df.format(new Date())); transferRequest(channel, received); } else if (received.getMessage() == ProtocolMessage.LOGOUT_REQUEST) { String userName = received.getHeaderLine(0); ps.printf("[Solicitação de logout (%s): %s]\n", userName, df.format(new Date())); logoutRequest(channel, received); } else if (received.getMessage() == ProtocolMessage.HEART_BEAT) { String userName = received.getHeaderLine(0); ps.printf("[Hear beat (%s): %s]\n", userName, df.format(new Date())); heartBeat(received); } }
096a5b1b-eb93-49c7-a639-a02597a31eb6
3
public static String getParentPath(String path) { if (path != null) { int index = path.lastIndexOf(mxCellPath.PATH_SEPARATOR); if (index >= 0) { return path.substring(0, index); } else if (path.length() > 0) { return ""; } } return null; }
2a5cba6c-a050-4b59-8bb8-d73b2ded40a1
1
public MainWindow () { setTitle("Camp Planer " + versionString); setSize(800, 600); setMinimumSize(new Dimension(500, 300)); // import setup data try { System.out.println ("Trying to read setup file " + SETUP_FILE_NAME + "."); setupData = SetupData.read (SETUP_FILE_NAME); } catch (Exception e) { System.out.println ("Could not read setup file. Using default setup."); System.out.println (e); setupData = new SetupData (); } eventOptionsDialog = new EventOptionsDialog (this); computerOptionsDialog = new ComputerOptionsDialog(this); createMenuBar (); // Create JTabbedPane object JTabbedPane tabpane = new JTabbedPane (JTabbedPane.TOP,JTabbedPane.SCROLL_TAB_LAYOUT ); // create panel to edit trip information tripDBPanel = new TripDBPanel(); tripDBPanel.setBackground(Color.LIGHT_GRAY); tabpane.addTab("Fahrten", tripDBPanel); // create panel to edit river information riverDBPanel = new RiverDBPanel(); tabpane.addTab("Fl\u00FCsse", riverDBPanel); // create panel to edit roster information rosterDBPanel = new RosterDBPanel(); rosterDBPanel.setBackground(Color.GREEN); setupData.addPropertyChangeListener(rosterDBPanel); tabpane.addTab("Fahrtenleiter", rosterDBPanel); // add tabs to window add(tabpane); aboutDialog = new About (this); readFromFile(setupData.getDataFileName()); }
32cde072-ba24-4182-b699-cfda6d27b55a
4
public static int[] string2int( String[] splits ) throws NullPointerException, NumberFormatException { if( splits == null ) return null; int[] arr = new int[ splits.length ]; for( int i = 0; i < splits.length; i++ ) { if( splits[i] == null ) throw new NullPointerException( "Token at index " + i + " is null and cannot be converted to int." ); try { arr[i] = Integer.parseInt( splits[i].trim() ); } catch( NumberFormatException e ) { throw new NullPointerException( "Token at index " + i + " does not represent an int." ); } } return arr; }
bd268145-f73b-4d5b-a820-1f96de482e66
4
@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((attrs == null) ? 0 : attrs.hashCode()); result = prime * result + (endTag ? 1231 : 1237); result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + (selfClosing ? 1231 : 1237); return result; }
50cd2e4a-3194-4e61-8546-da925c8ee766
4
public static <T> SimilarityDatabase<T> create(final Similarity<? super T> distance, Iterable<? extends T> candidates) { BKTree.Builder<T> builder = BKTree.createBuilder(distance); for (T crnt : candidates) { builder.insert(crnt); } final BKTree root = builder.build(); final BasicNeighborhoodQuery.Builder<T> queryBuilder = BasicNeighborhoodQuery.Builder.<T>create(distance); return new SimilarityDatabase<T>() { public Iterable<? extends T> find(T target, int tolerance) { return queryBuilder.centeredAt(target).closerThan(tolerance).build().search(root); } }; }
90486d56-0b73-421c-bd3f-323926204d34
5
public void stopMonitor() { if (this.disableBillTypes(this.STOP_ENTER_POINT)) { for (int i=0; i<30; i++) { if (this.poll(true)) { if (this.deviceAnswerSTATE.equals("Unit Disabled")) { if (!this.STOP_GET_MONEY_CALLBACK.equals("")) return; } } } } this.STOP_GET_MONEY_CALLBACK = ""; this.powerUpAndReset(true); // если не остановил прием купюр, делаем обнуление }
cf840d44-6403-4081-9624-3b0e66661d2a
8
@Override public void run() { ReceiverBot rb = BotManager.getInstance().receiverBot; if (!rb.isConnected() || (rb.checkStalePing() && BotManager.getInstance().monitorPings)) { try { System.out.println("INFO: Attempting to reconnect receiver"); rb.disconnect(); Thread.currentThread().sleep(20000); if (!rb.isConnected()) rb.reconnect(); } catch (NickAlreadyInUseException e) { System.out.println("Nickname already in use - " + rb.getNick() + " " + rb.getServer()); } catch (IOException e) { System.out.println("Unable to connect to server - " + rb.getNick() + " " + rb.getServer()); } catch (IrcException e) { System.out.println("Error connecting to server - " + rb.getNick() + " " + rb.getServer()); } catch (InterruptedException e) { System.out.println("Threading execption occured - " + rb.getNick() + " " + rb.getServer()); } } }
0600b0ad-8af7-4a93-8c61-aa3cdfced79a
3
public Tiedote validateAndConvert() throws ValidointiPoikkeus { // luodaan wrapper virheiden kuljettamista varten ValidointiVirheet virheet = new ValidointiVirheet(); // luodaan validoija Validator validoija = new Validator(); Tiedote tiedote = new Tiedote(); // otsikon validointi if (validoija.validateString(this.otsikkoTeksti, "otsikko", "Otsikko", 35, true, false, false)) { tiedote.setOtsikko(otsikkoTeksti); } // tiedotteen tekstin validointi if (validoija.validateString(this.tiedoteTeksti, "tiedote", "Tiedote", 255, true, false, false)) { tiedote.setTiedote(tiedoteTeksti); } // kutsutaan virhe Map jos virheitä on ja lähetetään ne poikkeusluokalle if (validoija.getVirheet().size() > 0) { virheet = validoija.getVirheet(); throw new ValidointiPoikkeus(virheet); } else { return tiedote; } }
253b24cf-919b-45e0-bb8b-a79d55bb9c8b
3
public static List<Integer> getAllPrimesLessThen(int limit) { Sequence<Integer> primes = new ArrayedPrimesSequence(); int c = 0; try { List<Integer> primesList = new ArrayList<Integer>(limit / 5); while (true) { c++; int prime = primes.next(); if (prime > limit) { return primesList; } primesList.add(prime); } } catch (StackOverflowError e) { System.out.println("Error after " + c + " iterations."); } return null; }
984afcff-de9c-4abb-acea-b776d0d23248
1
public void testWithFieldAdded2() { Period test = new Period(1, 2, 3, 4, 5, 6, 7, 8); try { test.withFieldAdded(null, 0); fail(); } catch (IllegalArgumentException ex) {} }
ef537fd2-09be-402a-a646-ec5e98c124dd
7
private List<T> merge(List<T> leftList, List<T> rightList) { // Create the list that will contain the result (i.e., merge) of the two lists. List<T> mergedList = new ArrayList<T>(); // As long as either the left or the right list has items remaining in it that have not been // merged, continue removing the elements in order and building up the merged list. while (leftList.size() > 0 || rightList.size() > 0) { // Case 1: Both lists have elements remaining. if (leftList.size() > 0 && rightList.size() > 0) { if (leftList.get(0).compareTo(rightList.get(0)) < 0) { // Left list contains next smallest element, so remove it and add it to the merged list. mergedList.add(leftList.remove(0)); } else { // Right list contains next smallest element, so remove it and add it to the merged list. mergedList.add(rightList.remove(0)); } continue; } // Case 2: Only the left list has elements remaining (we would not get to this point // in the code if the rightList.size() > 0), so the next smallest elements must be in the // left list. if (leftList.size() > 0) { // Remove the next element in the left list, which will be the next smallest element, and // add it to the merged list. mergedList.add(leftList.remove(0)); continue; } // Case 3: Only the right list has elements remaining if (rightList.size() > 0) { // Remove the next element in the right list, which will be the next smallest element, and // add it to the merged list. mergedList.add(rightList.remove(0)); continue; } } return mergedList; }
77245903-d6fd-4eec-9e6d-f1e02d89497f
4
private void displayHeader() { // Calculate width and pad with '-': int width = fieldWidth * tests.size() + sizeWidth; int dashLength = width - headline.length() - 1; StringBuilder head = new StringBuilder(width); for(int i = 0; i < dashLength / 2; i++) head.append('-'); head.append(' '); head.append(headline); head.append(' '); for(int i = 0; i < dashLength / 2; i++) head.append('-'); System.out.println(head); // Print column headers: System.out.format(sizeField, "size"); for(Test<?> test : tests) { System.out.format(stringField(), test.name); } System.out.println(); }
8899e250-f89f-4c90-9b2c-687e71e97cbb
0
public synchronized static boolean isDone() { return done; }
64e4ddfd-93f7-46d6-8559-ef735d4bdef6
7
public void userDataEvent(VisualizePanelEvent e) { if (m_propertyDialog != null) { m_propertyDialog.dispose(); m_propertyDialog = null; } try { if (m_focus != null) { double wdom = e.getInstances1().numInstances() + e.getInstances2().numInstances(); if (wdom == 0) { wdom = 1; } TreeClass tmp = m_focus; m_focus.m_set1 = new TreeClass(null, e.getAttribute1(), e.getAttribute2(), m_nextId, e.getInstances1().numInstances() / wdom, e.getInstances1(), m_focus); m_focus.m_set2 = new TreeClass(null, e.getAttribute1(), e.getAttribute2(), m_nextId, e.getInstances2().numInstances() / wdom, e.getInstances2(), m_focus); //this needs the other instance //tree_frame.getContentPane().removeAll(); m_focus.setInfo(e.getAttribute1(), e.getAttribute2(), e.getValues()); //System.out.println(graph()); m_tView = new TreeVisualizer(this, graph(), new PlaceNode2()); //tree_frame.getContentPane().add(m_tView); //tree_frame.getContentPane().doLayout(); m_reps.setComponentAt(0, m_tView); m_focus = m_focus.m_set2; m_tView.setHighlight(m_focus.m_identity); m_iView.setInstances(m_focus.m_training); if (tmp.m_attrib1 >= 0) { m_iView.setXIndex(tmp.m_attrib1); } if (tmp.m_attrib2 >= 0) { m_iView.setYIndex(tmp.m_attrib2); } m_iView.setColourIndex(m_focus.m_training.classIndex()); if (((Double)((FastVector)m_focus.m_ranges.elementAt(0)). elementAt(0)).intValue() != LEAF) { m_iView.setShapes(m_focus.m_ranges); } //m_iView.setSIndex(2); } else { System.out.println("Somehow the focus is null"); } } catch(Exception er) { System.out.println("Error : " + er); System.out.println("Part of user input so had to catch here"); //er.printStackTrace(); } }
d03f4366-4e2a-4fdb-bf35-ae467e2de8f8
4
private static void parseIngredientsForInitialDataRepository(Node IngredientNode, Vector<Ingredient> RestIngredients) { if (IngredientNode.getNodeType() == Node.ELEMENT_NODE) { Element IngredientsElement = (Element) IngredientNode; String ingredientName= IngredientsElement.getElementsByTagName("name").item(0).getTextContent(); int ingredientQuantity= Integer.decode(IngredientsElement.getElementsByTagName("quantity").item(0).getTextContent()); if((ingredientName == null) || (ingredientName == "")) throw (new RuntimeException("ingredientName is null or empty string!")); if(ingredientQuantity < 0) throw (new RuntimeException("toolQuantity is negetive!")); Ingredient newIngredient= new Ingredient(ingredientName, ingredientQuantity); RestIngredients.add(newIngredient); } }
c7a27d67-0711-4893-adad-fa90b2b28264
4
private void setupForDragging(MouseEvent e) { source.addMouseMotionListener(this); potentialDrag = true; // Determine the component that will ultimately be moved if (destinationComponent != null) { destination = destinationComponent; } else if (destinationClass == null) { destination = source; } else // forward events to destination component { destination = SwingUtilities.getAncestorOfClass(destinationClass, source); } pressed = e.getLocationOnScreen(); location = destination.getLocation(); if (changeCursor) { originalCursor = source.getCursor(); source.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR)); } // Making sure autoscrolls is false will allow for smoother dragging of // individual components if (destination instanceof JComponent) { JComponent jc = (JComponent) destination; autoscrolls = jc.getAutoscrolls(); jc.setAutoscrolls(false); } }
a10a0837-c2da-43e0-a1b3-09fd067a245c
0
protected JComponent initTreePanel() { treeDrawer.setNodeDrawer(nodeDrawer); return super.initTreePanel(); }
193000d5-348f-492d-a385-7f87324ec4d9
4
static public void FixInconsitencies(){ Map<String, LastActivity> lastActivities = LastActivity.lastActivities; Player[] players = AFKPGC.plugin.getServer().getOnlinePlayers(); TreeSet<String> playersTree = new TreeSet<String>(); for(Player p:players) { String name = p.getName(); if(!lastActivities.containsKey(name)) AFKPGC.addPlayer(p.getName()); playersTree.add(name); } String[] keySet = lastActivities.keySet().toArray(new String[0]); for(String i:keySet){ if(!playersTree.contains(i)) AFKPGC.removerPlayer(i); } }
11ca4785-eff1-4456-8676-dd6ac568b454
3
public static void main(String[] args) throws UnknownHostException, IOException, NumberFormatException, InterruptedException { // Connect to the server socket = new Socket("localhost", PORT); // Write and read from the server through sockets out = new PrintWriter(socket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); // Create a new instance of a client PongClient client = new PongClient(); // Wait for the ACTIVE method to start the client while (true) { String message = in.readLine(); if (message != null) { if (message.startsWith("ACTIVE")) { client.ID = Integer.parseInt(message.substring("ACTIVE".length() + 1)); game.setID(Integer.parseInt(message.substring("ACTIVE".length() + 1))); client.setActive(); break; } } } }
d3f9dc48-6c4c-4801-8368-8137040d276f
3
@Override public void run() { try { connect(server, port); if (serverEventsListener != null) serverEventsListener.connected(); } catch (IOException | IrcException e) { if (serverEventsListener != null) serverEventsListener.connectionCantBeEstabilished( e.getMessage() ); } }
c627a5b0-a7e3-4a49-a1b0-4bca2ce60a62
6
public static int areConnected(WayOsm w1, WayOsm w2){ if(w1 == null || w2 == null) return -1; if(w1.getNodes().get(w1.getNodes().size()-1).equals(w2.getNodes().get(0))) return 1; if(w1.getNodes().get(0).equals(w2.getNodes().get(w2.getNodes().size()-1))) return 2; if(w1.getNodes().get(0).equals(w2.getNodes().get(0))) return 3; if(w1.getNodes().get(w1.getNodes().size()-1).equals(w2.getNodes().get(w2.getNodes().size()-1))) return 4; return 0; }
8e496189-60d1-4df3-ae26-216e0fb7c340
6
public void mouseMoved(MouseEvent e) { performAutoScrollIfActive(e); if (mapViewer.isGotoStarted()) { if (mapViewer.getActiveUnit() == null) { mapViewer.stopGoto(); } Tile tile = mapViewer.convertToMapTile(e.getX(), e.getY()); if (tile != null) { if (lastTile != tile) { Unit active = mapViewer.getActiveUnit(); lastTile = tile; if (active != null && active.getTile() != tile) { PathNode dragPath = active.findPath(tile); mapViewer.setGotoPath(dragPath); } else { mapViewer.setGotoPath(null); } } } } }
2e808710-2a9f-4b94-a188-f9851fac5064
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(CadastrarUser.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(CadastrarUser.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(CadastrarUser.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(CadastrarUser.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 CadastrarUser().setVisible(true); } }); }
c27c2d3a-0cc0-401f-bd4e-5c37ada43156
7
public void setPassable(int x, int y, Direction dir, boolean v) { if(dir == Direction.RIGHT) { setPassable(x + 1, y , Direction.LEFT, v); return; } if(dir == Direction.DOWN ) { setPassable(x , y + 1, Direction.UP , v); return; } if(check(x, y)) { if(x == 0 && dir == Direction.LEFT) { return; } if(y == 0 && dir == Direction.UP ) { return; } pass[x][y][dir.ordinal()] = v; } }
a3d98de9-42e8-48b1-b52d-097cc8b39423
5
protected void getVertxBufferOutputStream(String fileName, Handler<AsyncResult<InputStream>> doneHandler) { vertx.fileSystem().open(fileName, null, false, false, false, result -> { if (result.failed()) { doneHandler.handle(new SimpleAsyncResult<>(result.cause())); return; } PipedOutputStream os = new PipedOutputStream(); try { InputStream is = new PipedInputStream(os); doneHandler.handle(new SimpleAsyncResult<>(is)); } catch (Exception e) { doneHandler.handle(new SimpleAsyncResult<>(e)); return; } result.result().dataHandler(data -> { try { os.write(data.getBytes()); } catch (Exception e) { container.logger().warn("Failed to read " + fileName, e); try { //os.close(); result.result().close(); } catch (Exception ex) { container.logger().debug("Failed to close stream after reading " + fileName, e); } } }); result.result().endHandler(v -> { try { os.close(); } catch (Exception e) { container.logger().debug("Failed to close stream after reading " + fileName, e); } }); }); }
6ee23560-42d3-4b18-91d2-1c59e73f90e0
4
public void run() { while(!playerChanges.isEmpty()) { PlayerOnlineChange change = playerChanges.poll(); if (change == null) return; if (change.getOnline()) OnlineUsers.ds.addUser(change.getName(), change.getUUID()); else if (OnlineUsers.removeOfflineUsers) OnlineUsers.ds.removeUser(change.getName(), change.getUUID()); else OnlineUsers.ds.setUserOffline(change.getName(), change.getUUID()); } }
84bf20e9-c6fa-4b5f-8b04-281d3b37f762
9
private void resetTarget() { System.out.println("\n--------- reset redex ----------"); //System.out.println(this); if (target == null) { // handle the information about module Equation[] eqs = (Equation[])(module.equations.toArray()); Hashtable op2eq = new Hashtable(); for (int i=0; i<eqs.length; i++) { Term left = eqs[i].getLeft(); if (left.getTopOperation() != null) { Vector tmp = (Vector)op2eq.get(left.getTopOperation().getName()); if (tmp == null) tmp = new Vector(); tmp.addElement(eqs[i]); op2eq.put(left.getTopOperation().getName(), tmp); } } Vector conside = new Vector(); if (operation != null) { conside = (Vector)op2eq.get(operation.getName()); } //System.out.println("\n======== conside for term "+term); //System.out.println(conside); if (conside == null) { conside = new Vector(); } for (int i=0; i<conside.size(); i++) { Equation eq = (Equation)conside.elementAt(i); Term left = eq.getLeft(); Term right = eq.getRight(); Term cond = eq.getCondition(); Hashtable var2term = getMatch(this.toTerm(), left); //System.out.println("what ==== "+var2term); if (var2term != null ) { Enumeration e = var2term.keys(); while (e.hasMoreElements()) { Variable var = (Variable)e.nextElement(); Term trm = (Term)var2term.get(var); right = right.subst(var, trm); } //System.out.println("find equation: "+eq); //System.out.println("right: "+right); target = new ReducedTerm(right, module); break; } } } System.out.println("------ done ------"); }
4f244e0c-9a7e-4102-83e8-68aae680a9b3
3
public void paintComponent(Graphics g) { if (myImage == null) return; Rectangle r = getVisibleRect(), r2 = new Rectangle(getPreferredSize()); int offsetx = r.width > r2.width ? (r.width - r2.width) / 2 : 0; int offsety = r.height > r2.height ? (r.height - r2.height) / 2 : 0; r = r.intersection(r2); g.drawImage(myImage, r.x + offsetx, r.y + offsety, r.x + r.width + offsetx, r.y + r.height + offsety, r.x, r.y, r.x + r.width, r.y + r.height, this); }
6ae799c6-318c-4f19-8004-605e027359d2
2
@Override public void keyPressed(KeyEvent e) { if (!(e.getKeyCode() == KeyEvent.VK_C && e.isControlDown())) { e.consume(); } }
fddd560c-4833-433a-8174-dec5669ad093
4
private void assignActionsToButtons() { bLoad.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { File f = FileUtil.showSavegameLoadDialog(controlPanel); if(f != null) { savegame = f; savegameLocation.setText(savegame.getAbsolutePath()); updateButtonStates(); parseFile(); } } }); bRetry.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(savegame.getAbsolutePath().endsWith(".dat")) { parseFile(); } else { JOptionPane.showMessageDialog(controlPanel, "Something derped! Please try to select the file again.", "Derp", JOptionPane.WARNING_MESSAGE); } } }); bSave.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { editor.applyAllChanges(); } catch(Exception ex) { MessageUtil.error("Failed to Save:\n\n" + ex.getClass().toString() + ": " + ex.getMessage()); return; } File f = FileUtil.showSaveDialog(controlPanel, savegame); if(f != null) { storeFile(f); } } }); }
d9458aba-11bc-455d-856e-9ebd284cd8e4
5
public String ViewMySQLPackets(DatabaseAccess JavaDBAccess) { Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; String MySQLPackets = ""; try { if ((conn = JavaDBAccess.setConn()) != null) { System.out.println("Connected to database " + JavaDBAccess.getDatabaseName()); } else { throw new Exception("Not connected to database " + JavaDBAccess.getDatabaseName()); } conn.setAutoCommit(false); // Start a transaction by inserting a record in the TARGET_PHP_FILES_FUNCTIONS table ps = conn.prepareStatement("SELECT ID,THIS_THREAD_ID,PEER_THREAD_ID,PROXY_PACKET,PACKET_TIMESTAMP FROM MYSQL_PROXY_PACKETS"); rs = ps.executeQuery(); while (rs.next()) { Blob Packet = rs.getBlob("PROXY_PACKET"); byte[] b; char ch; b = Packet.getBytes(1, (int) Packet.length()); ch = (char) b[1]; for (int i = 1; i <= Packet.length(); i++) { MySQLPackets = MySQLPackets + i + " <-> " + Integer.toHexString(Packet.getBytes(i, 1)[0] & 0xff).toUpperCase() + "\r\n"; // & 0xff is to convert byte to unsigned int } MySQLPackets = MySQLPackets + "\r\n"; // System.out.println(MySQLPackets); } rs.close(); ps.close(); conn.commit(); conn.close(); } catch (Throwable e) { System.out.println("exception thrown:"); if (e instanceof SQLException) { JavaDBAccess.printSQLError((SQLException) e); } else { e.printStackTrace(); } } return MySQLPackets; }
1b65768e-a8a6-415a-86c2-59edde5a269e
4
public void invertObjects() { for(int i = 0; i < inputRecordsPerDumpList.size(); i++) { long record = inputRecordsPerDumpList.get(i); UserObjectsPerDump objects = userObjsPerDumpList.get(i); for(UserObject obj : objects.getUesrObjects()) { if(obj.getCode().equals(function)) { if(!objectName_index.containsKey(obj.getObjectName())) { SizeModel model = new SizeModel(obj.getObjectName()); model.add(record, obj); objectSizeModelList.add(model); objectName_index.put(obj.getObjectName(), objectSizeModelList.size() - 1); } else { int index = objectName_index.get(obj.getObjectName()); SizeModel model = objectSizeModelList.get(index); model.add(record, obj); } } } } }
e7c0eecf-bc2a-46c7-8a23-e889d6658059
1
public void setNext() { for (int x = 0; x < 4; x++) { System.arraycopy(grid[x], 0, next.grid[x], 0, 4); } }
20dc3169-c6e5-4b60-a207-475cd0037e55
2
public void undoLastMove() { if (!this.moveList.empty()) { Move lastMove = this.moveList.pop(); lastMove.undo(); this.setTurn(lastMove.player); // Change turn to player whose turn was just undone this.redoList.add(lastMove); if (this.activeField != null) { this.activeField.makeInactive(); this.activeField = null; } } }
13f27839-6201-4738-a262-b1ef57ba2fa9
0
public PrimitiveUndoableReplace(Node parent, Node oldNode, Node newNode) { this.parent = parent; this.oldNode = oldNode; this.newNode = newNode; this.index = oldNode.currentIndex(); }
780e9441-f006-4a8c-9127-e388c5a1b848
4
public boolean collision(int x, int y, int a, int b, int w, int h){ boolean up=(y-b)<h; boolean down=(y-b)>0; boolean left=(x-a)<w; boolean right=(x-a)>0; if(left&&right&&up&&down){ return true; } return false; }
5a4b0a9f-a53c-474c-b5f2-25047013300f
1
public void visit_lshr(final Instruction inst) { stackHeight -= 3; if (stackHeight < minStackHeight) { minStackHeight = stackHeight; } stackHeight += 2; }
e7a15b60-44b5-46f4-823e-937e21d86b52
2
private void removeDisconnectedClientEntities(final long clientDisconnectedID) { for (Entity e : entityMap.values()) { if (e.getClientId() == clientDisconnectedID) e.setDeleteTimeleft(500); } }