text
stringlengths
14
410k
label
int32
0
9
private void notifyOfSort(boolean restoring) { for (OutlineModelListener listener : getCurrentListeners()) { listener.sorted(this, restoring); } }
1
private void read(SocketChannelExtender socket) { int result = socket.read(readBuffer); if ((result & RES_CLOSE_SOCKET) != 0) { closeSocketPair(socket); readBuffer.clear(); return; } if ((result & RES_ALLOCATE_BUFFER) != 0) { readBuffer = new RWSocketChannelBuffer(DEFAULT_BUFFER_SIZE); } else { readBuffer.clear(); } if ((result & RES_WRITE_PAIR_SOCKET) != 0) { SelectionKey secondKey = socket.getSecondChannel().getChannel().keyFor(selector); if (secondKey != null) { secondKey.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE); } } if ((result & RES_WRITE_DATA_END) != 0) { SelectionKey secondKey = socket.getSecondChannel().getChannel().keyFor(selector); if (secondKey != null) { secondKey.interestOps(SelectionKey.OP_READ); } } }
6
public synchronized void setBeanContext(BeanContext bc) throws PropertyVetoException { // Do nothing if the old and new values are equal if ((this.beanContext == null) && (bc == null)) { return; } if ((this.beanContext != null) && this.beanContext.equals(bc)) { return; } // Children are not allowed to repeatedly veto this operation. // So, we set rejectedSetBCOnce flag to true if veto occurs // and never veto the change again if (!(this.rejectedSetBCOnce && this.lastVetoedContext == bc)) { this.lastVetoedContext = bc; this.rejectedSetBCOnce = true; // Validate the new BeanContext value and throw // PropertyVetoException if it was not successful if (!validatePendingSetBeanContext(bc)) { throw new PropertyVetoException(Messages.getString("beans.0F"), //$NON-NLS-1$ new PropertyChangeEvent(this.beanContextChildPeer, BEAN_CONTEXT, this.beanContext, bc)); } fireVetoableChange(BEAN_CONTEXT, this.beanContext, bc); } this.rejectedSetBCOnce = false; releaseBeanContextResources(); // We have to notify all listeners about "beanContext" // property change firePropertyChange(BEAN_CONTEXT, this.beanContext, bc); this.beanContext = bc; initializeBeanContextResources(); //} }
7
private void scale(final float m, final float[] a, final int offa) { int nthreads = ConcurrencyUtils.getNumberOfThreads(); if ((nthreads > 1) && (n > ConcurrencyUtils.getThreadsBeginN_1D_FFT_2Threads())) { nthreads = 2; final int k = n / nthreads; Future<?>[] futures = new Future[nthreads]; for (int i = 0; i < nthreads; i++) { final int firstIdx = offa + i * k; final int lastIdx = (i == (nthreads - 1)) ? offa + n : firstIdx + k; futures[i] = ConcurrencyUtils.submit(new Runnable() { public void run() { for (int i = firstIdx; i < lastIdx; i++) { a[i] *= m; } } }); } ConcurrencyUtils.waitForCompletion(futures); } else { int firstIdx = offa; int lastIdx = offa + n; for (int i = firstIdx; i < lastIdx; i++) { a[i] *= m; } } }
7
@Override public void selectionChanged(TreeSelectionEvent e) { JoeTree tree = e.getTree(); Document doc = tree.getDocument(); if (doc == Outliner.documents.getMostRecentDocumentTouched()) { if (tree.getComponentFocus() == OutlineLayoutManager.ICON) { setEnabled(true); } else { setEnabled(false); } } }
2
private Invoice createInvoiceObjectFromResponse(HttpResponse response) throws IOException, JSONException { BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuilder content = new StringBuilder(); String line; while (null != (line = rd.readLine())) { content.append(line); } Object obj=JSONValue.parse(content.toString()); JSONObject finalResult = (JSONObject)obj; if(finalResult.get("error") != null ){ System.out.println("Error: " + finalResult.get("error")); } return new Invoice(finalResult); };
2
public void playSoundtrack() { if (this.soundtrack != null) {// sometimes is not loaded at the first // time this.soundtrack.play(); // if(this.soundtrack.isPlaying()){ // this.soundtrack.setLooping(true); // } // long id = this.soundtrack.play(); // this.soundtrack.setLooping(id, true); } }
1
@Override public <T> T unwrap(Class<T> arg0) throws SQLException { return null; }
0
public void activate(final boolean activate) { active = activate; if (active && getCache() == null) setCache(new LFUCache(0, 0)); // supply a really simple "all you can buffer"-filter if (active && nwFilter == null) { nwFilter = new NetworkFilter() { public void accept(final CEMI frame, final Configuration c) { final Cache localCache = c.getCache(); if (localCache == null || !(frame instanceof CEMILData)) return; final CEMILData f = (CEMILData) frame; // put into cache object final CacheObject co = localCache.get(f.getDestination()); if (co != null) { ((LDataObject) co).setFrame(f); c.getCache().put(co); } else localCache.put(new LDataObject(f)); } public void init(final Configuration c) {} }; } // we might not have any filter if we get deactivated on first call if (nwFilter != null) nwFilter.init(this); }
8
public InternetExplorerLauncher(BrowserConfigurationOptions browserOptions, RemoteControlConfiguration configuration, String sessionId, String browserLaunchLocation) { String mode = browserOptions.get("mode"); if (mode == null) mode = DEFAULT_MODE; if ("default".equals(mode)) mode = DEFAULT_MODE; if (DEFAULT_MODE.equals(mode)) { realLauncher = new HTABrowserLauncher(browserOptions, configuration, sessionId, browserLaunchLocation); return; } boolean proxyInjectionMode = browserOptions.is("proxyInjectionMode") || "proxyInjection".equals(mode); // You can't just individually configure a browser for PI mode; it's a server-level configuration parameter boolean globalProxyInjectionMode = configuration.getProxyInjectionModeArg(); if (proxyInjectionMode && !globalProxyInjectionMode) { if (proxyInjectionMode) { throw new RuntimeException("You requested proxy injection mode, but this server wasn't configured with -proxyInjectionMode on the command line"); } } // if user didn't request PI, but the server is configured that way, just switch up to PI proxyInjectionMode = globalProxyInjectionMode; if (proxyInjectionMode) { realLauncher = new ProxyInjectionInternetExplorerCustomProxyLauncher(browserOptions, configuration, sessionId, browserLaunchLocation); return; } // the mode isn't "chrome" or "proxyInjection"; at this point it had better be "proxy" if (!"proxy".equals(mode)) { throw new RuntimeException("Unrecognized browser mode: " + mode); } realLauncher = new InternetExplorerCustomProxyLauncher(browserOptions, configuration, sessionId, browserLaunchLocation); }
9
private boolean checkValid(int x, int y) { boolean[] row = new boolean[9]; boolean[] col = new boolean[9]; for (int i = 0; i < 9; i++) { char rowChar = board[x][i]; char colChar = board[i][y]; if (rowChar != '.') { if (row[rowChar - '1']) return false; else row[rowChar - '1'] = true; } if (colChar != '.') { if (col[colChar - '1']) return false; else col[colChar - '1'] = true; } } for (int i = 0; i < 9; i++) row[i] = false; x = (x / 3) * 3; y = (y / 3) * 3; for (int k = 0; k < 9; k++) { char blockChar = board[x + (k/3)][y + (k%3)]; if (blockChar != '.') { if (row[blockChar - '1']) return false; else row[blockChar - '1'] = true; } } return true; }
9
public void wdgmsg(Widget sender, String msg, Object... args) { if(busy){return;} if(sender == content) { String request = (String)args[0]; if((Integer)args[1] == 1) { open(request); } else { new WikiPage(ui.wiki, request, true); } } else if(sender == cbtn) { ui.destroy(this); } else { super.wdgmsg(sender, msg, args); } }
4
public void test_01() { // Run String args[] = { "-classic", "-ud", "0", "testHg3766Chr1", "./tests/test.mnp.01.vcf" }; SnpEff cmd = new SnpEff(args); SnpEffCmdEff snpeff = (SnpEffCmdEff) cmd.snpEffCmd(); List<VcfEntry> results = snpeff.run(true); // Check Assert.assertEquals(1, results.size()); VcfEntry result = results.get(0); for (VcfEffect eff : result.parseEffects()) { String aa = eff.getAa(); String aaNumStr = aa.substring(1, aa.length() - 1); int aanum = Gpr.parseIntSafe(aaNumStr); System.out.println(eff.getAa() + "\t" + aaNumStr + "\t" + eff); if (aanum <= 0) throw new RuntimeException("Missing AA number!"); } }
2
public static boolean hasSpace(){ for (Item item : inventory) { if(item == null) return true; } return false; }
2
private void handleStartProcess(String[] cmdLine){ if(cmdLine.length < 3){ System.out.println("invalid argument, see help for more information"); return; } int workerId; try{ workerId = Integer.valueOf(cmdLine[1]); }catch(Exception e){ System.out.println("the worker id is not a number"); return; } if(!workersMap.containsKey(workerId)){ System.out.println("there is no worker with id number "+workerId); return; } /*pass all the checkes, now get the argument for the process*/ String[] args = new String[cmdLine.length - 3]; for(int i=3;i<cmdLine.length;i++){ args[i-3] = cmdLine[i]; } /*try{ Class process = ProcessManager.class.getClassLoader().loadClass(cmdLine[2]); }catch(ClassNotFoundException e){ System.out.println("no such process class "+cmdLine[2]); return; }*/ processId++; Message cmdMessage = new Message(Message.msgType.COMMAND); cmdMessage.setCommandId(CommandType.START); cmdMessage.setArgs(args); cmdMessage.setProcessName(cmdLine[2]); cmdMessage.setProcessId(processId); if(processServerMap.containsKey(workerId)){ try{ processServerMap.get(workerId).sendToWorker(cmdMessage); ProcessInfo procInfo = new ProcessInfo(); procInfo.setId(processId); procInfo.setName(cmdLine[2]); procInfo.setWorkerId(workerId); procInfo.setStatus(Status.STARTING); processesMap.put(processId, procInfo); }catch (IOException e) { //e.printStackTrace(); System.out.println("start Command sent failed, remove worker "+workerId); removeNode(workerId); } } else{ System.out.println("there is no server for workerId "+workerId); } }
6
public void set(String name, Object value) { try { Scanner scan = new Scanner(this); File temp = new File("temp"); PrintWriter pw = new PrintWriter("temp"); boolean used = false; while(scan.hasNextLine()) { String line = scan.nextLine(); if(line.startsWith(name)) { line = name + ":" + value.toString(); used = true; } pw.write(line + "\n"); } if(!used) pw.write(name + ":" + value.toString()); pw.close(); scan = new Scanner(temp); pw = new PrintWriter(this); this.delete(); this.createNewFile(); while(scan.hasNextLine()) pw.write(scan.nextLine() + "\n"); pw.close(); }catch(Exception ex) { BaseUtils.warn(ex, true); } }
5
public Compras() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 450, 366); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JButton btn_Cadastrar = new JButton("Cadastrar"); btn_Cadastrar.setBounds(311, 47, 89, 23); contentPane.add(btn_Cadastrar); JButton btn_Remover = new JButton("Remover"); btn_Remover.setBounds(311, 110, 89, 23); contentPane.add(btn_Remover); JButton btn_Atualizar = new JButton("Atualizar"); btn_Atualizar.setBounds(311, 181, 89, 23); contentPane.add(btn_Atualizar); JButton btn_Voltar = new JButton("Voltar"); btn_Voltar.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { new Oficina().setVisible(true); fecharJFrame(); } }); btn_Voltar.setBounds(296, 11, 114, 23); contentPane.add(btn_Voltar); final JLabel lbl_error = new JLabel(""); lbl_error.setBounds(27, 301, 223, 16); contentPane.add(lbl_error); final JList list_compras = new JList(); list_compras.setBounds(24, 29, 252, 229); final DefaultListModel model = new DefaultListModel(); for(Iterator<Compra> iter = OficinaFacade.comprasIterator();iter.hasNext();){ Compra compra = (Compra)iter.next(); try { model.addElement(compra.getId() + "(" + OficinaFacade.buscarConta(compra.getContaCPF()).getNome() +")"); } catch (ContaNaoExisteException e1) { e1.printStackTrace(); } catch (CPFInvalidoException e1) { e1.printStackTrace(); } } list_compras.setModel(model); contentPane.add(list_compras); btn_Cadastrar.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if(!OficinaFacade.contaIterator().hasNext()){ //Pois senao a compra nao existira. lbl_error.setText("Nao Existem contas cadastradas para efetuarem compras."); }else if(!OficinaFacade.servicoIterator().hasNext()){ lbl_error.setText("N�o existem servi�os cadastrados para se constituir uma compra"); }else{ new CadastrarCompra().setVisible(true); fecharJFrame(); } } }); btn_Remover.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(list_compras.getSelectedValue() != null){ String ID = list_compras.getSelectedValue().toString().substring(list_compras.getSelectedValue().toString().indexOf("(", 0)+1,list_compras.getSelectedValue().toString().length()-1); try { OficinaFacade.removerServico(ID); model.removeElement(list_compras.getSelectedValue()); } catch (ServicoNaoEncontradoException e1) { e1.printStackTrace(); } }else{ lbl_error.setText("Nenhum cliente selecionado."); } } }); btn_Atualizar.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String ID = list_compras.getSelectedValue().toString().substring(0,list_compras.getSelectedValue().toString().indexOf("(")); AtualizarCompra frame = new AtualizarCompra(); frame.setVisible(true); try { frame.selecionarDados(OficinaFacade.buscarCompra(ID)); } catch (CompraNaoExisteException e1) { e1.printStackTrace(); } //Passa os dados necessarios de uma GUI para a outra. fecharJFrame(); } }); }
8
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; IngredientList other = (IngredientList) obj; if (ingredientList == null) { if (other.ingredientList != null) return false; } else if (!ingredientList.equals(other.ingredientList)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; }
9
@Override public void grantAbilities(MOB mob, boolean isBorrowedRace) { final PairList<Ability,AbilityMapping> onesToAdd=new PairVector<Ability,AbilityMapping>(); for(final Enumeration<Ability> a=CMClass.abilities();a.hasMoreElements();) { final Ability A=a.nextElement(); final AbilityMapping mapping = CMLib.ableMapper().getQualifyingMapping(ID(), false, A.ID()); if((mapping != null) &&(mapping.qualLevel()>0) &&(mapping.qualLevel()<=mob.phyStats().level()) &&(mapping.autoGain())) { final String extraMask=mapping.extraMask(); if((extraMask==null) ||(extraMask.length()==0) ||(CMLib.masking().maskCheck(extraMask,mob,true))) onesToAdd.add(A,mapping); } } for(int v=0;v<onesToAdd.size();v++) { final Ability A=onesToAdd.get(v).first; final AbilityMapping map=onesToAdd.get(v).second; giveMobAbility(mob,A,map.defaultProficiency(),map.defaultParm(),isBorrowedRace); } }
9
public tracuuphong(int khu, String phong, String loai, String quanly,DefaultTableModel tb) { if(khu==0)khui="b5"; if(khu==1)khui="b6"; if(khu==3)khui="b7"; String maphong; maphong= khui+"-"+phong; if (phong.length() == 0) { JOptionPane.showMessageDialog(null, "Bạn cần nhập từ khóa để tìm", "Thông báo", 1); } else { try { Statement stmt = c.createStatement(); String sql="select loaiphong,quanlynha from nha,phong where nha.tennha=phong.nha and maph='"+maphong+"';"; ResultSet rs1=stmt.executeQuery(sql); while(rs1.next()){ this.quanly=rs1.getString(2); this.loai=rs1.getString(1); } column = new Vector(); String sql1="select mssv,ten,khoa,ngayvao from sinhvien where maph = '"+maphong+"';"; ResultSet rs2=stmt.executeQuery(sql1); ResultSetMetaData metaData=rs2.getMetaData(); numbercolumn=metaData.getColumnCount(); for(int i=1;i<=numbercolumn;i++){ column.add(metaData.getColumnName(i)); } this.tb.setColumnIdentifiers(column); while(rs2.next()){ row=new Vector(); for(int i=1;i<=numbercolumn;i++){ row.add(rs2.getString(i)); } this.tb.addRow(row); } stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } }
9
public void keyPressed(KeyEvent e) { int key = e.getKeyCode(); if (key == KeyEvent.VK_LEFT) { battlefield.getMuzzle().setAngle(battlefield.getMuzzle().getAngle() - battlefield.getMuzzle().getSpeed()); } else if (key == KeyEvent.VK_RIGHT) { battlefield.getMuzzle().setAngle(battlefield.getMuzzle().getAngle() + battlefield.getMuzzle().getSpeed()); } else if (key == KeyEvent.VK_CONTROL) { Muzzle muzzle = getBattlefield().getMuzzle(); if (battlefield.getShotFreq() <= battlefield.getCurrentShot()) { battlefield.getMuzzle().setFire(true); try { as = new AudioStream(this.getClass().getClassLoader().getResourceAsStream("shot.wav")); } catch (FileNotFoundException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } p.start(as); getBattlefield().getWhizbangs().add(new Whizbang(muzzle.getTrans(), muzzle.getAngle())); battlefield.setCurrentShot(0); } } }
6
public void open () { //Check for saving the current file if (checkSaved ()){ final Lawgbook l = display.getLawgbook (); File file; //This crashed a few times with a nullpointerException fileChooser.showOpenDialog(this); //I need to access a component for this to work. May have to move location of IO Methods file = fileChooser.getSelectedFile(); if (file != null){ //Create temporary arrayLists in case something goes wrong final ArrayList<Activity> a = new ArrayList<Activity>(); a.addAll (l.getActivities()); final ArrayList<Student> st = new ArrayList<Student>(); st.addAll (l.getStudents()); final ArrayList<Lesson> lessons = new ArrayList<Lesson>(); lessons.addAll (l.getLessons()); final String oldTitle = l.getTitle(); final int [] stats = new int []{l.getTotalWeeks(),l.getWeeksPassed(),l.getActivityMin(),l.getLessonTime()}; class Restore { public void restoreData (){ l.clearData(); l.getActivities().addAll(a); l.getStudents().addAll (st); l.getLessons().addAll (lessons); l.setTitle (oldTitle); l.setTotalWeeks (stats [0]); l.setWeeksPassed (stats[1]); l.setActivityMin (stats [2]); l.setLessonTime (stats [3]); } } try{ BufferedReader in = new BufferedReader (new FileReader (file)); l.clearData(); //read in all the info in.readLine ();//The header l.setTitle (in.readLine ()); l.setTotalWeeks (Integer.parseInt (in.readLine ())); l.setWeeksPassed (Integer.parseInt (in.readLine ())); l.setActivityMin (Integer.parseInt (in.readLine ())); l.setLessonTime (Integer.parseInt (in.readLine())); int numActivities = Integer.parseInt (in.readLine()); for (int x = 0;x < numActivities;x++){ String name = in.readLine (); int completed = Integer.parseInt (in.readLine ()); int time = Integer.parseInt (in.readLine()); int numItems = Integer.parseInt (in.readLine ()); ArrayList<String> items = new ArrayList<String>(); for (int y = 0;y < numItems;y++){ items.add (in.readLine()); } Activity ac = new Activity (name,completed); ac.setTime (time); ac.setItems (items); l.addActivity (ac); } int numStudents = Integer.parseInt (in.readLine ()); for (int x = 0;x < numStudents;x++){ String name = in.readLine (); l.addStudent (name); Student s = l.getStudent (x); for (int y = 0;y < numActivities;y++){ String aName = in.readLine (); int rank = Integer.parseInt (in.readLine ()); s.setRanking (aName,rank); } } int numLessons = Integer.parseInt (in.readLine ()); for (int x = 0;x < numLessons;x++){ String title = in.readLine(); long time = Long.parseLong(in.readLine ()); Date newDate = new Date (time); int listLength = Integer.parseInt (in.readLine ()); ArrayList<Activity> list = new ArrayList<Activity>(); for (int y = 0;y < listLength;y++){ list.add (l.getActivity (in.readLine())); } String comments = in.readLine (); l.addLesson (new Lesson (title,newDate,list,comments)); } in.readLine ();//footer in.close(); //Do all checks to make sure the data is all good //necessary status changes l.setSaved (true); l.setFile (file); //Display the info show ("display"); } catch (IOException e) { JOptionPane.showMessageDialog (this,"File could not be found.","File IO error",JOptionPane.ERROR_MESSAGE); } //could clear this up with a nested method // catch (NumberFormatException n) // { // (new Restore()).restoreData (); // JOptionPane.showMessageDialog (this,"Corrupted Data.","File IO error",JOptionPane.ERROR_MESSAGE); // } // catch (NullPointerException p) // { // (new Restore()).restoreData (); // JOptionPane.showMessageDialog (this,"Corrupted Data.","File IO error",JOptionPane.ERROR_MESSAGE); // } } } }
9
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //On verifie le parametre email existe String email = request.getParameter("email"); if (email ==null){ request.setAttribute("message", "Le email n'est pas spécifié."); request.getRequestDispatcher("/index.jsp").forward(request, response);return; } try {//On s'assure qu'il n'existe pas de compte avec ce nom for(MembreDAO dao:new MembreDAO[]{ new HotelierDAO(), new ParticulierDAO(), } ) if(dao.read(email)!=null){ request.setAttribute("message", "Il existe déjà un compte qui utilise de courriel."); request.getRequestDispatcher("/index.jsp").forward(request, response);return; } } catch(ClassNotFoundException ex){ request.setAttribute("message", "Impossible de se connceter à la base de données."); request.getRequestDispatcher("/index.jsp").forward(request, response); } String type = request.getParameter("type"); if(type ==null){ request.setAttribute("message", "Le type de compte à creer n'est pas spécifié."); request.getRequestDispatcher("/index.jsp").forward(request, response);return; } type=type.toLowerCase(); Membre membre; if(type.equals("hotelier")) try{ membre = this.createHotelier(request); } catch(Exception e){ request.setAttribute("message", e.getMessage()); request.getRequestDispatcher("/index.jsp").forward(request, response);return; } else if (type.equals("particulier")){ try{ membre = this.createParticulier(request); } catch(Exception e){ request.setAttribute("message", e.getMessage()); request.getRequestDispatcher("/index.jsp").forward(request, response);return; } } else{ request.setAttribute("message", "Ce type de compte n'existe pas."); request.getRequestDispatcher("/index.jsp").forward(request, response);return; } request.getSession().setAttribute("connecte", membre); request.getSession().setAttribute("typecompte", type); request.getRequestDispatcher("/index.jsp").forward(request, response); }
9
public void setClassName(String className) { this.className = className; }
0
private void initArrays() { if (data == null || picsize != data.length) { data = new int[picsize]; magnitude = new int[picsize]; xConv = new float[picsize]; yConv = new float[picsize]; xGradient = new float[picsize]; yGradient = new float[picsize]; } }
2
private void leftCtrlClickAction(int x, int y) { if (!isEditable()) { leftShiftClickAction(x, y); return; } if (isTile(x, y)) { if (selection[x][y] == -1 && selt != 1) { selection[x][y] = getArrangementData(x, y); } else if (selection[x][y] != -1 && selt != 0) { setArrangementData(x, y, selection[x][y]); selection[x][y] = -1; } repaint(); } }
6
public String getBilan() { return bilan; }
0
public void addSupportedFeatures(String supportsString) { String[] stringFeatureReps = supportsString.replace("$Supports ","").split("\\s+"); for (String stringFeature : stringFeatureReps) { try { stringFeature = stringFeature.replace("\\|", ""); SupportsFeature feature = SupportsFeature.valueOf(stringFeature); supportedFeatures.add(feature); } catch (IllegalArgumentException e){ //no such supports feature. swallow error } } }
2
public void actionPerformed(ActionEvent event) { // JFrame frame = Universe.frameForEnvironment(environment); try { getExpression().asCheckedString(); } catch (UnsupportedOperationException e) { JOptionPane.showMessageDialog(getEnvironment(), e.getMessage(), "Illegal Expression", JOptionPane.ERROR_MESSAGE); return; } ConvertToAutomatonPane pane = new ConvertToAutomatonPane( getEnvironment()); getEnvironment().add(pane, "Convert RE to NFA", new CriticalTag() { }); getEnvironment().setActive(pane); }
1
public Deplacement PrecedentDeplacement(int i) { Deplacement deplacementPrecedent = null; Tour touractuelle = null; int j =0; for (Tour tour : historiqueToursJoueur) { touractuelle = tour; for (Deplacement deplacement : tour.getListDeplacement()) { j++; if(j == (i)) { deplacementPrecedent = deplacement; break; } } } if (deplacementPrecedent!=null && touractuelle !=null ){ //recuperation de la couleur de la dame manger CouleurCase CaseArriverSaveCouleur; if (deplacementPrecedent.getCaseArriver().getCouleurDame() == CouleurCase.BLANC) CaseArriverSaveCouleur = CouleurCase.NOIR; else CaseArriverSaveCouleur = CouleurCase.BLANC; tablier.deplacerDame(deplacementPrecedent.getCaseArriver(),deplacementPrecedent.getCaseDepart()); if(deplacementPrecedent.isSiCaseBattue()) { tablier.deplacerDame(tablier.getCaseBarre(CaseArriverSaveCouleur),deplacementPrecedent.getCaseArriver()); } } return deplacementPrecedent; }
7
public static void testParametreReservation (String nomS, String dateS, String numS) throws BDException { String requete = "select * from lesspectacles, lesrepresentations where lesspectacles.numS=lesrepresentations.numS and lesspectacles.numS="+numS+" and dateRep = to_date('"+dateS+"','dd/mm/yyyy hh24:mi') and nomS='"+nomS+"'"; Statement stmt = null; ResultSet rs = null; Connection conn = null; try { conn = BDConnexion.getConnexion(); stmt = conn.createStatement(); rs = stmt.executeQuery(requete); if (!rs.next()) { throw new BDExceptionIllegal(""); } } catch (SQLException e) { throw new BDException("Problème dans l'interrogation des spectacles et représentations (Code Oracle : "+e.getErrorCode()+")"); } finally { BDConnexion.FermerTout(conn, stmt, rs); } }
2
public void testForFields_time_HMm() { DateTimeFieldType[] fields = new DateTimeFieldType[] { DateTimeFieldType.hourOfDay(), DateTimeFieldType.minuteOfHour(), DateTimeFieldType.millisOfSecond(), }; int[] values = new int[] {10, 20, 40}; List types = new ArrayList(Arrays.asList(fields)); DateTimeFormatter f = ISODateTimeFormat.forFields(types, true, false); assertEquals("10:20-.040", f.print(new Partial(fields, values))); assertEquals(0, types.size()); types = new ArrayList(Arrays.asList(fields)); f = ISODateTimeFormat.forFields(types, false, false); assertEquals("1020-.040", f.print(new Partial(fields, values))); assertEquals(0, types.size()); types = new ArrayList(Arrays.asList(fields)); try { ISODateTimeFormat.forFields(types, true, true); fail(); } catch (IllegalArgumentException ex) {} types = new ArrayList(Arrays.asList(fields)); try { ISODateTimeFormat.forFields(types, false, true); fail(); } catch (IllegalArgumentException ex) {} }
2
@Override public boolean isWebDriverType(String type) { return StringUtils.equalsIgnoreCase("phantomjs", type); }
0
public K findKey (Object value, boolean identity) { V[] valueTable = this.valueTable; if (value == null) { K[] keyTable = this.keyTable; for (int i = capacity + stashSize; i-- > 0;) if (keyTable[i] != null && valueTable[i] == null) return keyTable[i]; } else if (identity) { for (int i = capacity + stashSize; i-- > 0;) if (valueTable[i] == value) return keyTable[i]; } else { for (int i = capacity + stashSize; i-- > 0;) if (value.equals(valueTable[i])) return keyTable[i]; } return null; }
9
private void copyPixels(int destOff, int width, int height, int srcStep, int srcOff, int destStep, int src[], int dest[]) { int quarterX = -(width >> 2); width = -(width & 3); for (int i = -height; i < 0; i++) { for (int j = quarterX; j < 0; j++) { dest[destOff++] = src[srcOff++]; dest[destOff++] = src[srcOff++]; dest[destOff++] = src[srcOff++]; dest[destOff++] = src[srcOff++]; } for (int k = width; k < 0; k++) { dest[destOff++] = src[srcOff++]; } destOff += destStep; srcOff += srcStep; } }
3
public String getAddress2() { return address2; }
0
private void revealNeighbouringCards(Rectangle removedCardArea, int rowOfRemovedCard) { int previousRow = rowOfRemovedCard - 1; int nextRow = rowOfRemovedCard + 1; /* * Stage 7 (20 Marks) */ int checkRow; switch (rowOfRemovedCard) { case 1: checkRowOfNeighbours(removedCardArea, checkRow = 0, rowOfRemovedCard); break; case 3: checkRowOfNeighbours(removedCardArea, checkRow = 4, rowOfRemovedCard); break; case 2: checkRowOfNeighbours(removedCardArea, checkRow = 1, rowOfRemovedCard); checkRowOfNeighbours(removedCardArea, checkRow = 3, rowOfRemovedCard); break; } }
3
public Long getId() { return id; }
0
public static DoHouseWork getSingleton(){ // needed because once there is singleton available no need to acquire // monitor again & again as it is costly if(singleton==null) { synchronized(DoHouseWork.class){ // this is needed if two threads are waiting at the monitor at the // time when singleton was getting instantiated if(singleton==null) singleton = new DoHouseWork(); } } return singleton; }
2
public static void main(String[] args) throws IOException { if (args.length == 1) { Webserver web = new Webserver(args[0]); web.run(); } else System.err.println( "Usage: java javassist.tools.web.Webserver <port number>"); }
1
private void initGUI() { setFocusable(true); this.setBorder(null); MouseAdapter mouseListener = new MouseAdapter() { @Override public void mouseEntered(java.awt.event.MouseEvent evt) { mouseIsOverButton = true; setBackground(); } @Override public void mouseExited(java.awt.event.MouseEvent evt) { mouseIsOverButton = false; setBackground(); } @Override public void mousePressed(java.awt.event.MouseEvent evt) { if (SwingUtilities.isLeftMouseButton(evt)) { mouseIsDown = true; setBackground(); } } @Override public void mouseReleased(java.awt.event.MouseEvent evt) { mouseIsDown = false; if (!isEnabled() || !SwingUtilities.isLeftMouseButton(evt)) return; if (mouseIsOverButton) fireActionPerformed(new ActionEvent(JdotxtImageButton.this, ActionEvent.ACTION_PERFORMED, "Click")); setBackground(); } }; addMouseListener(mouseListener); FocusListener focusListener = new FocusListener() { @Override public void focusLost(FocusEvent arg0) { focused = false; setBackground(); } @Override public void focusGained(FocusEvent arg0) { focused = true; setBackground(); } }; addFocusListener(focusListener); KeyListener keyListener = new KeyListener() { @Override public void keyTyped(KeyEvent e) { } @Override public void keyReleased(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ENTER || e.getKeyCode() == KeyEvent.VK_SPACE) { keyIsPressed = false; setBackground(); fireActionPerformed(new ActionEvent(JdotxtImageButton.this, ActionEvent.ACTION_PERFORMED, "Click")); } } @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ENTER || e.getKeyCode() == KeyEvent.VK_SPACE) { keyIsPressed = true; setBackground(); } } }; addKeyListener(keyListener); }
8
@Override public void onPluginMessageReceived(String channel, Player player, byte[] message) { if(!channel.equals(MESSAGING_CHANNEL)) return; DataInputStream in = new DataInputStream(new ByteArrayInputStream(message)); try { String subchannel = in.readUTF(); if(subchannel.equals("Forward")) { String mychannel = in.readUTF(); if(mychannel.equals(DONATION_MESSAGING_CHANNEL)) { byte[] msgbytes = new byte[in.readShort()]; in.readFully(msgbytes); DataInputStream msgin = new DataInputStream(new ByteArrayInputStream(msgbytes)); plugin.getDonationManager().tryDonation(DonationID.getByID(msgin.readInt()), msgin.readUTF()); } else if(mychannel.equals(VOTE_MESSAGING_CHANNEL)) { byte[] msgbytes = new byte[in.readShort()]; in.readFully(msgbytes); DataInputStream msgin = new DataInputStream(new ByteArrayInputStream(msgbytes)); UEVote vote = new UEVote(msgin.readUTF(), msgin.readUTF(), msgin.readUTF(), msgin.readUTF()); plugin.getServer().getPluginManager().callEvent(new UEVoteReceiveEvent(vote)); } } } catch (IOException e) { e.printStackTrace(); } }
5
public static void set(String key, Serializable value) { synchronized (data) { Serializable old = data.put(key, value); if (((old == null) && (value != null)) || ((old != null) && (!old.equals(value)))) modified = true; } }
4
public GetQuestionsFromMySqlDatabase(String hostname, String databaseName, String username, String password) { this.hostname = hostname; this.databaseName = databaseName; this.username = username; this.password = password; }
0
void Stand_Up(float dt) { int i; int onfloor = 0; float scale = 2.0f; // touch the feet to the floor for(i=0;i<6;++i) { if(legs[i].ankle_joint.pos.z>0) legs[i].ankle_joint.pos.z-=4*scale*dt; else ++onfloor; // contract - put feet closer to shoulders Vector3f df = new Vector3f(legs[i].ankle_joint.pos); df.sub(body.pos); df.z=0; if(df.length()>standing_radius) { df.normalize(); df.scale(6*scale*dt); legs[i].ankle_joint.pos.sub(df); } } if(onfloor==6) { // we've planted all feet, raise the body a bit if( body.pos.z < standing_height ) body.pos.z+=2*scale*dt; for(i=0;i<6;++i) { Vector3f ds = new Vector3f( legs[i].pan_joint.pos ); ds.sub( body.pos ); ds.normalize(); ds.scale(standing_radius); legs[i].npoc.set(body.pos.x+ds.x, body.pos.y+ds.y, 0); } } }
6
@Override public void run() { List<UIEvent> lastEvents = Model.getModel().getInteractionStack().getLastEvents(2); if (lastEvents.get(0).getEventType() != EventType.MOUSE_BUTTON_UP || lastEvents.get(0).getButton() != 1 || lastEvents.get(1).getEventType() != EventType.MOUSE_BUTTON_DOWN || Model.getModel().getActionSelection().isEmpty() || Model.getModel().getSimpleSelection().isEmpty()) { return; } // IMPROVE Clean this : we use a Selectable, when we would need a Ship. // Therefore, we have an extraneous cast. // However, we might attack something else than ships ... Entity targetShip = Model.getModel().getActionSelection().getFirst(); if (!(targetShip instanceof Ship)) { return; } for (Entity selectable : Model.getModel().getSimpleSelection()) { if (selectable instanceof Ship && selectable != targetShip) { Ship ship = (Ship) selectable; // Remove existing movement and combat behaviors ship.removeBehaviorsByClass(Movement.class); ship.removeBehaviorsByClass(InflictLaserDamage.class); // Add new arrive behavior ship.addBehavior(new Follow(selectable, targetShip, InflictLaserDamage.MAX_RANGE * 0.5f)); // Add new combat behavior InflictLaserDamage inflictLaserDamage = new InflictLaserDamage(ship, targetShip); ship.addBehavior(inflictLaserDamage); } } }
9
public static void main(String[] args) { int matriceA[][] = {{1, 1, 1, 1, 1}, {2, 2, 2, 2, 2}, {3, 3, 3, 3, 3}, {4, 4, 4, 4, 4}, {5, 5, 5, 5, 5}}; int matriceB[][] = new int[matriceA.length][matriceA[0].length]; int i; int j; for(i = 0; i < matriceA.length; i++) for(j = 0; j < matriceA[i].length; j++) matriceB[j][i] = matriceA[i][j]; for(i = 0; i < matriceA.length; i++) { for(j = 0; j < matriceA[i].length; j++) System.out.print(matriceA[i][j]+" "); System.out.print("\t"); for(j = 0; j < matriceA[i].length; j++) System.out.print(matriceB[i][j]+" "); System.out.print("\n"); } System.exit(0); }
5
public void _jspService(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException { PageContext pageContext = null; HttpSession session = null; ServletContext application = null; ServletConfig config = null; JspWriter out = null; Object page = this; JspWriter _jspx_out = null; PageContext _jspx_page_context = null; try { response.setContentType("text/html"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; _jspx_resourceInjector = (org.glassfish.jsp.api.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector"); out.write("\n"); out.write("\n"); out.write("\n"); Class.forName("oracle.jdbc.OracleDriver") ; out.write('\n'); String name = request.getParameter( "v2" ); session.setAttribute( "theValue", name ); out.write("\n"); out.write("\n"); out.write("<html>\n"); out.write(" <HEAD>\n"); out.write(" <TITLE>List of agents and number of clients who have booked with them in descending \n"); out.write(" order</TITLE>\n"); out.write(" </HEAD>\n"); out.write("\n"); out.write(" <BODY>\n"); out.write(" <H1>List of agents and number of clients who have booked with them in descending \n"); out.write(" order</H1>\n"); out.write("\n"); out.write(" "); //String a=session.getAttribute("theValue"); Connection connection = DriverManager.getConnection( "jdbc:oracle:thin:@fourier.cs.iit.edu:1521:orcl", "mkhan12", "sourov345"); Statement statement = connection.createStatement() ; ResultSet resultset = statement.executeQuery("select Book_id,Booking.agentID,Booking.clientID,firstnm,lastnm, Date_Booking,Resort_name,Arrival_date,Dept_date,Room.Room_type_name from Booking,Client,Resort,Room,Agent where firstnm=" +"'" +session.getAttribute("theValue")+"'" +"and Booking.clientID=Client.clientID and Booking.Resort_id=Resort.Resort_id and " + "Booking.Room_type_id=Room.Room_type_id and Booking.agentID=Agent.agentID" ) ; out.write("\n"); out.write("\n"); out.write(" <TABLE BORDER=\"1\">\n"); out.write(" <TR>\n"); out.write(" <TH>Book ID</TH>\n"); out.write(" <TH>Agent ID</TH>\n"); out.write(" <TH>Client ID</TH>\n"); out.write(" <TH>First Name</TH>\n"); out.write(" <TH>Last Name</TH>\n"); out.write(" <TH>Booking Date</TH> \n"); out.write(" <TH>Resort </TH>\n"); out.write(" <TH>Arrival Date</TH>\n"); out.write(" <TH>Departure Date</TH>\n"); out.write(" <TH>Room Type </TH>\n"); out.write(" \n"); out.write(" \n"); out.write(" \n"); out.write(" \n"); out.write(" \n"); out.write(" </TR>\n"); out.write(" "); while(resultset.next()){ out.write("\n"); out.write(" <TR>\n"); out.write(" <TD> "); out.print( resultset.getString(1) ); out.write("</td>\n"); out.write(" <TD> "); out.print( resultset.getString(2) ); out.write("</td>\n"); out.write(" <TD> "); out.print( resultset.getString(3) ); out.write("</td>\n"); out.write(" <TD> "); out.print( resultset.getString(4) ); out.write("</td>\n"); out.write(" <TD> "); out.print( resultset.getString(5) ); out.write("</td>\n"); out.write(" <TD> "); out.print( resultset.getString(6) ); out.write("</td>\n"); out.write(" <TD> "); out.print( resultset.getString(7) ); out.write("</td>\n"); out.write(" <TD> "); out.print( resultset.getString(8) ); out.write("</td>\n"); out.write(" <TD> "); out.print( resultset.getString(9) ); out.write("</td>\n"); out.write(" <TD> "); out.print( resultset.getString(10) ); out.write("</td>\n"); out.write(" \n"); out.write(" \n"); out.write(" \n"); out.write(" \n"); out.write(" \n"); out.write(" </TR>\n"); out.write(" "); } out.write("\n"); out.write(" </TABLE>\n"); out.write(" </BODY>\n"); out.write("</html>\n"); } catch (Throwable t) { if (!(t instanceof SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize() != 0) out.clearBuffer(); if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); else throw new ServletException(t); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } }
6
@Test public void runTestApplicationLifecycle1() throws IOException { InfoflowResults res = analyzeAPKFile("Lifecycle_ApplicationLifecycle1.apk"); Assert.assertEquals(1, res.size()); }
0
public static Proposition normalizeValueFunction(Proposition self) { { Surrogate functionsurrogate = Logic.evaluateRelationTerm((self.arguments.theArray)[0], self); int newargumentcount = self.arguments.length() - 1; Proposition newproposition = null; Proposition duplicate = null; if (functionsurrogate == null) { return (self); } newproposition = Logic.createProposition(Logic.SYM_STELLA_FUNCTION, newargumentcount); newproposition.operator = functionsurrogate; { int i = Stella.NULL_INTEGER; int iter000 = 1; int upperBound000 = newargumentcount; boolean unboundedP000 = upperBound000 == Stella.NULL_INTEGER; for (;unboundedP000 || (iter000 <= upperBound000); iter000 = iter000 + 1) { i = iter000; (newproposition.arguments.theArray)[(i - 1)] = ((self.arguments.theArray)[i]); } } if (Logic.skolemP((self.arguments.theArray)[(self.arguments.length() - 1)])) { ((Skolem)((self.arguments.theArray)[(self.arguments.length() - 1)])).definingProposition = newproposition; } if (!(Logic.descriptionModeP())) { duplicate = Proposition.findDuplicateFunctionProposition(newproposition); if (duplicate != null) { newproposition = duplicate; } } return (newproposition); } }
6
public void setAdapt(boolean newAdapt) { adapt = newAdapt; transformNeedsReform = true; repaint(); }
0
public static void Edit(){ FileReader pl=null; String what; String sCurrentLine=""; Scanner scan = new Scanner(System.in); what = scan.nextLine(); System.out.println("Input file:\n"); try{ //pl = new FileReader(f); pl = new FileReader("src/data"); } catch (FileNotFoundException e) { System.out.println("Opening file error!"); System.exit(1); } BufferedReader bfr = new BufferedReader(pl); try{ while((sCurrentLine = bfr.readLine()) != null){ System.out.println(sCurrentLine); sCurrentLine = sCurrentLine.replaceAll(what, ""); writer.save_me(sCurrentLine); } } catch (IOException e){ e.printStackTrace(); } finally { try { if (bfr != null)bfr.close(); } catch (IOException ex) { ex.printStackTrace(); } } }
5
private ResGridlet cancelReservationGridlet(int reservationID) { ResGridlet rgl = null; // Find in EXEC List first int found = findGridlet(gridletInExecList_, reservationID); if (found >= 0) { // update the gridlets in execution list up to this point in time updateGridletProcessing(); // Get the Gridlet from the execution list rgl = (ResGridlet) gridletInExecList_.remove(found); // if a Gridlet is finished upon cancelling, then set it to success // instead. if (rgl.getRemainingGridletLength() == 0.0) { rgl.setGridletStatus(Gridlet.SUCCESS); } else { rgl.setGridletStatus(Gridlet.CANCELED); } // Set PE on which Gridlet finished to FREE super.resource_.setStatusPE( PE.FREE, rgl.getMachineID(), rgl.getPEID() ); allocateQueueGridlet(); return rgl; } // Find in QUEUE list found = findGridlet(gridletQueueList_, reservationID); if (found >= 0) { rgl = (ResGridlet) gridletQueueList_.remove(found); rgl.setGridletStatus(Gridlet.CANCELED); return rgl; } // if not found, then find in the Paused list found = findGridlet(gridletPausedList_, reservationID); if (found >= 0) { rgl = (ResGridlet) gridletPausedList_.remove(found); rgl.setGridletStatus(Gridlet.CANCELED); return rgl; } // if not found, then find in AR waiting list found = findGridlet(gridletWaitingList_, reservationID); if (found >= 0) { rgl = (ResGridlet) gridletWaitingList_.remove(found); rgl.setGridletStatus(Gridlet.CANCELED); return rgl; } // if not found rgl = null; return rgl; }
5
public void setIpServer(String ip){ this.ipServer = ip; }
0
public void saveHitbox() { BufferedReader reader; try { reader = new BufferedReader(new FileReader(System.getProperty("resources") + "/database/entities")); String line; StringBuilder fileContent = new StringBuilder(); String newLine = null; while((line = reader.readLine()) != null) { String[] temp = line.split(";"); if(temp[0].matches(sprite.getName())) { newLine = sprite.getName() + ";" + chckbxSolid.isSelected() + ";" + textField_13.getText() + ";" + textField_14.getText() + ";" + textField_15.getText() + ";" + textField_16.getText(); fileContent.append(newLine); fileContent.append(System.getProperty("line.separator")); } else { fileContent.append(line); fileContent.append(System.getProperty("line.separator")); } } if(newLine == null) { newLine = sprite.getName() + ";" + chckbxSolid.isSelected() + ";" + textField_13.getText() + ";" + textField_14.getText() + ";" + textField_15.getText() + ";" + textField_16.getText(); fileContent.append(newLine); fileContent.append(System.getProperty("line.separator")); } BufferedWriter out = new BufferedWriter(new FileWriter(System.getProperty("resources") + "/database/entities")); out.write(fileContent.toString()); out.close(); reader.close(); } catch (FileNotFoundException e) { System.out.println("The entity database has been misplaced!"); e.printStackTrace(); } catch (IOException e) { System.out.println("Entity database failed to load!"); e.printStackTrace(); } }
5
public boolean opEquals(Operator o) { return (o instanceof LocalLoadOperator && ((LocalLoadOperator) o).local .getSlot() == local.getSlot()); }
1
public String operatorsToString(){ String str = new String(); for(Operator operand: operatorStack){ str = str + (operand.toString() + " "); } return str; }
1
public boolean isPrimitive() { if (clazz.isPrimitive()) { return true; } return is(Boolean.class) || is(Character.class) || is(Byte.class) || is(Short.class) || is(Integer.class) || is(Long.class) || is(Float.class) || is(Double.class) || is(Void.class); }
9
private void sendFile(){ try { FileReader fr = new FileReader(file); long numBytes = file.length(); char[] cbuf; byte[] buffer = new byte[PACKET_LENGTH]; System.arraycopy(ByteBuffer.allocate(4).putInt((int)numBytes/PACKET_LENGTH+2).array(), 0, buffer, 1, 4); buffer[0]=2; sendPacket(buffer); sendPacket(file.getName().getBytes()); for(int i=0;i<=numBytes/PACKET_LENGTH;i++){ if(numBytes > (i+1)*PACKET_LENGTH) cbuf = new char[PACKET_LENGTH]; else{ cbuf = new char[(int) (numBytes-((PACKET_LENGTH)*i))]; } fr.read(cbuf); sendPacket(new String(cbuf).getBytes()); _logger.log(new Message("send file part "+i+" out of"+ numBytes/PACKET_LENGTH,Message.Type.Report)); Thread.sleep(100); } } catch (FileNotFoundException e) { _logger.log(new Message("When getting file to send in \"Client\"", Message.Type.Error, e)); } catch (IOException e) { _logger.log(new Message("When reading file to send in \"Client\"", Message.Type.Error, e)); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
5
public void removeBit() { if (length == 0) { throw new IllegalStateException("no bits to remove"); } // Shift the bits one place to the right, losing the rightmost bit. bits = bits >> 1; length--; }
1
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { java.lang.String itemText = value != null ? value.toString() : ""; if( this.isViewerMode ) { // Item for current contents preview tool columnText.setIcon(this.iconViewCurrent); } else { // Regular copy/paste string items columnText.setIcon(UtilsClipboard.isInClipboard(itemText) ? this.iconDefault : this.iconHistoric); } columnText.setText(itemText); boolean hasFocus= list.hasFocus(); int hashCode = itemText.hashCode(); if (isSelected) { // Item is selected setBackground( hasFocus ? this.colorSelectionBackground : colorSelectionBackgroundNoFocus ); setForeground( this.colorSelectionForeground ); setBorder(cellHasFocus ? borderSelected : nonFocusBorder); if( this.isMac ) { this.columnText.setForeground( hasFocus ? JBColor.WHITE : JBColor.BLACK ); } } else { // Item is not selected int idColorTagged = Preferences.getIdColorByHashTag(hashCode); Color colorBackground = getColorByIndex(idColorTagged); Border border = getBorderByIndex(idColorTagged); setBorder( border ); setBackground( colorBackground ); setForeground(this.colorForeground); if( this.isMac ) { this.columnText.setForeground( this.colorForeground ); } } setOpaque(true); return this; }
9
public static final int StateInit() { return 0; }
0
private void Traversal(TreeNode root,ArrayList<Integer> list) { if(root != null){ Traversal(root.left,list); Traversal(root.right,list); list.add(root.val); } }
1
public LevelImporter() { addWindowListener(new WindowAdapter() { @Override public void windowClosed(WindowEvent e) { Game.get().display.getFrame().setVisible(true); } }); setResizable(false); setTitle("Image to Maze"); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setBounds(100, 100, 440, 190); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JButton btnChoseFile = new JButton("Chose file"); btnChoseFile.setBounds(10, 11, 153, 41); contentPane.add(btnChoseFile); textField_name = new JTextField(); textField_name.setBounds(173, 63, 251, 38); contentPane.add(textField_name); textField_name.setColumns(10); JLabel lblLevelName = new JLabel("Level Name"); lblLevelName.setFont(new Font("Arial", Font.PLAIN, 12)); lblLevelName.setBounds(10, 63, 153, 38); contentPane.add(lblLevelName); textField_file = new JTextField(); textField_file.setColumns(10); textField_file.setBounds(173, 11, 251, 38); contentPane.add(textField_file); JButton btnCreate = new JButton("Create"); btnCreate.setBounds(10, 112, 414, 41); contentPane.add(btnCreate); btnCreate.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { File file = new File(textField_file.getText()); if(!file.exists() || !file.getName().endsWith(".png")){ return; } BufferedImage i; try { i = ImageIO.read(file); } catch (IOException e1) { e1.printStackTrace(); return; } Raster r = i.getData(); Level l = Util.createEmptyLevel(r.getWidth(), r.getHeight() , textField_name.getText(), Color.white, Color.black, false); for(int x = 0; x<r.getWidth();x++){ for(int y = 0; y< r.getHeight(); y++){ if((i.getRGB(x, y)>>24) != 0x00 ){ l.getBlock(x, y).setType(Block.WALL); l.getBlock(x, y).setColor(new Color(i.getRGB(x, y))); } } } try { LevelLoader.SaveLevel(l, Folders.SAVES.getAbsolutePath() + "\\" + l.getName() + ".maze"); } catch (Exception e1) { e1.printStackTrace(); return; } disposer(); }}); }
7
private static void shuffle(Agent[] agents) { for (int i = 0; i < agents.length - 1; i++) { int j = prng.nextInt(agents.length - i) + i; Agent tmp = agents[j]; agents[j] = agents[i]; agents[i] = tmp; } }
1
public int readInt(String pSection, String pKey, int pDefault) { //if the ini file was never loaded from memory, return the default if (buffer == null) {return pDefault;} Parameters params = new Parameters(); //get the value associated with pSection and PKey String valueText = getValue(pSection, pKey, params); //if Section/Key not found, return the default if (valueText.equals("")) {return(pDefault);} int value; //try to convert the remainder of the string after the '=' symbol to an integer //if an error occurs, return the default value try{ value = Integer.parseInt(valueText); } catch(NumberFormatException e){return(pDefault);} return(value); }//end of IniFile::readInt
3
private final boolean method730(AbstractToolkit var_ha, Class72 class72_0_) { if (aClass105_1221 == null) { if (anInt1230 == 0) { if (Class101_Sub1.aD5684.method4(-7953, anInt1224)) { int[] is = Class101_Sub1.aD5684.method6(-21540, anInt1220, 0.7F, anInt1224, false, anInt1220); aClass105_1221 = var_ha.method3662(anInt1220, is, (byte) 94, 0, anInt1220, anInt1220); } } else if (anInt1230 == 2) method740(var_ha, class72_0_); else if (anInt1230 == 1) method735(var_ha, class72_0_); } if (aClass105_1221 == null) return false; return true; }
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(ContentHeirachy.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ContentHeirachy.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ContentHeirachy.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ContentHeirachy.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 ContentHeirachy().setVisible(true); } }); }
6
public int edmons_karp(int s, int t) { int u, e; mf = 0; this.s = s; Arrays.fill(p, -1); while (true) { f = 0; Queue<Integer> q = new LinkedList<Integer>(); int[] dist = new int[V]; Arrays.fill(dist, INF); dist[s] = 0; q.offer(s); Arrays.fill(p, -1); while (!q.isEmpty()) { u = q.poll(); if (u == t) break; for (int i = 0; i < ady[u].size(); i++) { e = ady[u].get(i); if (g[u][e] > 0 && dist[e] == INF) { dist[e] = dist[u] + 1; q.offer(e); p[e] = u;// parent of vertex e is vertex u } } } augment(t, INF); if (f == 0) break; mf += f; } return mf; }
7
private boolean interruptCalibration() { duration += nanoTime() - startTime; getEventHandler().handleEvent(new CalibrationMessage(epoch, sse, TimeUnit.MILLISECONDS.convert(duration, TimeUnit.NANOSECONDS))); if (isWalking()) { try { sleep(5l); startTime = nanoTime(); } catch (InterruptedException ex) { getLogger(NetworkController.class.getName()).log(Level.SEVERE, null, ex); duration = 0l; stopped = true; return true; } } if (isStepping() || isPaused()) { paused = true; return true; } return false; }
4
public void loadLower30DegreeSlope(Rectangle2D e) { for(int x = 0; x < TileSet.tileWidth / 2; x++) { platforms.add(new Platform(new Rectangle2D.Double(e.getX() + (2f * x), e.getCenterY() + x, 2f, 2f))); //System.out.println("Lower " + platforms.get(platforms.size() - 1).getBox().getY()); } }
1
@Override public void signalEndOfData() { // Do nothing }
0
private String decoderSerie(int u) { long D=((u%this.M)*(Outils.inverseModulo(this.W, this.M))%this.M)%this.M; String s=this.resoudreSacADosSuper(D,TAILLE_ENCODAGE-1); char[] c=s.toCharArray(); char temp=c[this.sigma1]; c[this.sigma1]=c[this.sigma2]; c[this.sigma2]=temp; String envers=""; for(int i=0;i<TAILLE_ENCODAGE/TAILLE_CHAR;i++) { int s2=0; for(int j=TAILLE_CHAR*i;j<TAILLE_CHAR*(i+1);j++) { if(c[c.length-1-j]=='1') { s2+=Math.pow(2, j-TAILLE_CHAR*i); } } envers+=(char)s2; } String aRetourner=""; for(int z=1;z<=envers.length();z++) { aRetourner+=envers.charAt(envers.length()-z); } return aRetourner; }
4
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(ResumeLookup.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ResumeLookup.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ResumeLookup.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ResumeLookup.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 ResumeLookup().setVisible(true); } }); }
6
public DirectionalBorderDetectorDialog(final Panel panel, final String title) { setTitle(title); this.panel = panel; setBounds(1, 1, 450, 250); Dimension size = getToolkit().getScreenSize(); setLocation(size.width / 3 - getWidth() / 3, size.height / 3 - getHeight() / 3); this.setResizable(false); setLayout(null); JPanel directionsPanel = new JPanel(); directionsPanel.setBorder(BorderFactory .createTitledBorder("Directions:")); directionsPanel.setBounds(0, 0, 450, 80); JPanel synthetizationPanel = new JPanel(); synthetizationPanel.setBorder(BorderFactory .createTitledBorder("Sinthetization:")); synthetizationPanel.setBounds(0, 80, 450, 80); final JCheckBox horizontalCheckBox = new JCheckBox("Horizontal", true); final JCheckBox verticalCheckBox = new JCheckBox("Vertical", true); final JCheckBox diagonalCheckBox = new JCheckBox("Diagonal", true); final JCheckBox otherDiagonalCheckBox = new JCheckBox("Inverse diagonal", true); final JRadioButton absRadioButton = new JRadioButton("Module", true); final JRadioButton maxRadioButton = new JRadioButton("Maximum"); final JRadioButton minRadioButton = new JRadioButton("Minimum"); final JRadioButton avgRadioButton = new JRadioButton("Average"); maxRadioButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { maxRadioButton.setSelected(true); minRadioButton.setSelected(!maxRadioButton.isSelected()); avgRadioButton.setSelected(!maxRadioButton.isSelected()); absRadioButton.setSelected(!maxRadioButton.isSelected()); } }); minRadioButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { minRadioButton.setSelected(true); maxRadioButton.setSelected(!minRadioButton.isSelected()); avgRadioButton.setSelected(!minRadioButton.isSelected()); absRadioButton.setSelected(!minRadioButton.isSelected()); } }); avgRadioButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { avgRadioButton.setSelected(true); maxRadioButton.setSelected(!avgRadioButton.isSelected()); minRadioButton.setSelected(!avgRadioButton.isSelected()); absRadioButton.setSelected(!avgRadioButton.isSelected()); } }); absRadioButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { absRadioButton.setSelected(true); maxRadioButton.setSelected(!absRadioButton.isSelected()); minRadioButton.setSelected(!absRadioButton.isSelected()); avgRadioButton.setSelected(!absRadioButton.isSelected()); } }); horizontalCheckBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { DirectionalBorderDetectorDialog.this.horizontal = horizontalCheckBox.isSelected(); } }); otherDiagonalCheckBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { DirectionalBorderDetectorDialog.this.inverseDiagonal = otherDiagonalCheckBox.isSelected(); } }); diagonalCheckBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { DirectionalBorderDetectorDialog.this.diagonal = diagonalCheckBox.isSelected(); } }); verticalCheckBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { DirectionalBorderDetectorDialog.this.vertical = verticalCheckBox.isSelected(); } }); JButton okButton = new JButton("OK"); okButton.setBounds(100, 180, 250, 40); okButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { SynthetizationType synthetizationType = null; if (!vertical && !horizontal && !diagonal && !inverseDiagonal) { new MessageFrame("Select a direction"); return; } if (maxRadioButton.isSelected()) { synthetizationType = SynthetizationType.MAX; } else if (minRadioButton.isSelected()) { synthetizationType = SynthetizationType.MIN; } else if (avgRadioButton.isSelected()) { synthetizationType = SynthetizationType.AVG; } else if (absRadioButton.isSelected()) { synthetizationType = SynthetizationType.ABS; } else { throw new IllegalStateException(); } DirectionalBorderDetectorDialog.this.applyFunction(synthetizationType); } }); directionsPanel.add(horizontalCheckBox); directionsPanel.add(verticalCheckBox); directionsPanel.add(diagonalCheckBox); directionsPanel.add(otherDiagonalCheckBox); synthetizationPanel.add(absRadioButton); synthetizationPanel.add(maxRadioButton); synthetizationPanel.add(minRadioButton); synthetizationPanel.add(avgRadioButton); add(directionsPanel); add(synthetizationPanel); add(okButton); }
8
private void buildHeap( Collection<? extends E> c ) { // move the elements of c into a complete binary tree // rooted at top heap = ( E[] ) c.toArray(); size = c.size(); // let cursor be the rightmost interior node int cursor = ( size / 2 ) - 1; // invariant: the children of cursor are valid heaps // while there are heaps to fix while ( cursor >= TOP ) { fixHeap( cursor ); // fix the heap rooted at cursor cursor--; // move cursor to the next // rightmost unvisited interior // node } }
2
@Override public void reset() { fp = null; if (input.isConnected()) { if (input.getSource() != null && input.getSource().getParent() != null) { this.setName("plot of " + input.getSource().getParent().getName() + "." + input.getSource().getName()); hist = new Hist(input.getSource().getParent().getName(), input .getSource().getName() + " trajectory", input.getSource().getName(), 1f); hist.setOrder(input.getDim()); } else { this.setName("plot"); hist = null; } } result = null; maxv = 0; }
3
public void updateStateBasedOnVelocity() { if(vx > 0) { setState(RIGHT); } else { setState(LEFT); } }
1
private boolean r_Step_4() { int among_var; int v_1; // (, line 129 // [, line 130 ket = cursor; // substring, line 130 among_var = find_among_b(a_6, 18); if (among_var == 0) { return false; } // ], line 130 bra = cursor; // call R2, line 130 if (!r_R2()) { return false; } switch(among_var) { case 0: return false; case 1: // (, line 133 // delete, line 133 slice_del(); break; case 2: // (, line 134 // or, line 134 lab0: do { v_1 = limit - cursor; lab1: do { // literal, line 134 if (!(eq_s_b(1, "s"))) { break lab1; } break lab0; } while (false); cursor = limit - v_1; // literal, line 134 if (!(eq_s_b(1, "t"))) { return false; } } while (false); // delete, line 134 slice_del(); break; } return true; }
9
public static void main(String [] args) throws IOException { // String start = "hit"; // String end = "cog"; // String [] dict = new String[]{"hot","dot","dog","lot","log"}; // HashSet<String> ds = new HashSet<String>(Arrays.asList(dict)); // // long s1 = System.currentTimeMillis(); // for(int i = 0; i < 1000; ++i) { //// System.out.println(new Word_Ladder().ladderLength(start, end, ds)); // new Word_Ladder().ladderLength(start, end, ds); // } // System.out.println(System.currentTimeMillis() - s1); // // long s2 = System.currentTimeMillis(); // for(int i = 0; i < 1000; ++i) { //// System.out.println(new Word_Ladder().ladderLength1(start, end, ds)); // new Word_Ladder().ladderLength1(start, end, ds); // } // System.out.println(System.currentTimeMillis() - s2); File f = new File("word_ladder.txt"); BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(f), "UTF-8")); String line = ""; HashSet<String> ds = new HashSet<String>(); while((line = reader.readLine()) != null){ ds.add(line); } String start = "nanny", end = "aloud"; long s1 = System.currentTimeMillis(); System.out.println(new Word_Ladder().ladderLength(start, end, ds)); System.out.println(System.currentTimeMillis() - s1); long s2 = System.currentTimeMillis(); System.out.println(new Word_Ladder().ladderLength1(start, end, ds)); System.out.println(System.currentTimeMillis() - s2); }
1
@Override public boolean supportsDocumentAttributes() {return false;}
0
private ArrayList<Bar> createBars(){ //arrange data lowest to highest Arrays.sort(data); int intervalSize = 0; if(numOfBars > 0) { intervalSize = (getMaxNumber(data) / numOfBars); } int lowerLimit = 0; int upperLimit = lowerLimit + intervalSize; int count; ArrayList<Bar> bars = new ArrayList<Bar>(numOfBars); for(int i = 0; i < numOfBars; i++) { count = 0; upperLimit = lowerLimit + intervalSize; for(int num : data){ if (num >= lowerLimit && num <= upperLimit){ count++; } } bars.add(new Bar(lowerLimit, upperLimit, count)); lowerLimit += intervalSize + 1; //add 1 so no overlap between intervals } return bars; }
5
private int firstEvenIndexOf(Object elem) { if (elem == null) { for (int i = 0; i < size(); i = i + 2) { if (get(i) == null) { return i; } } } else { for (int i = 0; i < size(); i = i + 2) { if (elem.equals(get(i))) { return i; } } } return -1; }
5
public void setRadius(double radius) { _radius = radius; }
0
public void ReadFile(Message inputMessage, int opID) { if(AddSharedParentLocks(inputMessage.filePath, opID)) { //Implement Later int indexCounter = 1; System.out.println("Master: trying to read "+inputMessage.filePath + indexCounter); if (!chunkServerMap.containsKey(inputMessage.filePath + indexCounter) && !NamespaceMap.containsKey(inputMessage.filePath + indexCounter)) { System.out.println("Master: doesnt exist"); SendErrorMessageToClient(inputMessage); return; } else if (!chunkServerMap.containsKey(inputMessage.filePath + indexCounter) && NamespaceMap.containsKey(inputMessage.filePath + indexCounter)) { //if the file exists in the chunkservermap and not in the namespacemap, it means that hte file is empty System.out.println("The file you desired is empty"); SendSuccessMessageToClient(inputMessage); return; } // check if the file contains multiple chunk indexes indexCounter++; synchronized(chunkServerMap) { while (chunkServerMap.containsKey(inputMessage.filePath + indexCounter)) { // ChunkMetadata cm = chunkServerMap.get(inputMessage.filePath + indexCounter); // Message returnMessage = new Message(msgType.READFILE, cm); // returnMessage.success = msgSuccess.REQUESTSUCCESS; // System.out.println("Master: found chunk number "+indexCounter +" of file. its hash is "+cm.chunkHash); // client.DealWithMessage(returnMessage); indexCounter++; } } //Send client the number of chunk number to read // client.ExpectChunkNumberForRead(indexCounter - 1); Message expectMsg = inputMessage; expectMsg.type = msgType.EXPECTEDNUMCHUNKREAD; expectMsg.success = msgSuccess.REQUESTSUCCESS; expectMsg.expectNumChunkForRead = indexCounter-1; SendMessageToClient(expectMsg); for(int i=1;i<indexCounter;i++){ ChunkMetadata cm = chunkServerMap.get(inputMessage.filePath+ i); //alter the list location synchronized(cm.listOfLocations){ for(ChunkLocation cl: cm.listOfLocations){ if(ServerMap.get(cl.chunkIP).status == HeartBeat.serverStatus.DEAD){ cm.listOfLocations.remove(cl); } } } System.out.println("Master: first chunkhash is "+cm.chunkHash); Message returnMessage = inputMessage; returnMessage.type = msgType.READFILE; returnMessage.chunkClass = cm; returnMessage.success = msgSuccess.REQUESTSUCCESS; SendMessageToClient(returnMessage); } } else { SendErrorMessageToClient(inputMessage); } }
9
@Override public void run() { try { server = new ServerSocket(7000); } catch (IOException e1) { e1.printStackTrace(); } try { System.out.println(new Date() + " --> Server waits for client..."); socket = server.accept(); // blocking System.out.println(new Date() + " --> Client connected from " + socket.getInetAddress() + ":" + socket.getPort()); vec = new LinkedList<>(); outputStream = new ObjectOutputStream(socket.getOutputStream()); inputStream = new ObjectInputStream(socket.getInputStream()); while(true){ vec = (Queue<Object>) inputStream.readObject(); for (Object obj : vec) { if (obj instanceof Missile) { missile = (Missile) obj; } if (obj instanceof Launcher) { launcher = (Launcher) obj; } } if (missile != null && launcher != null) { launcher = WarUtility.getLauncherById(launcher.getLauncherId(),war); System.out.println(launcher.getLauncherId()); missile = WarUtility.getMissileById(missile.getMissileId(), war); System.out.println(missile.getMissileId()); launcher.addMissile(missile); } else { war.addLauncher(launcher); System.out.println("only" + launcher.getLauncherId()); } vec.clear(); missile = null; launcher = null; System.out.println("server"); } } catch (Exception e) { System.out.println(e); } finally { } }
8
private Class<?> ensureReplacedClass(Scriptable scope, Object obj, Class<?> staticType) { final Class<?> type = (staticType == null && obj != null) ? obj .getClass() : staticType; if (!type.isPrimitive() && !type.getName().startsWith("java.") && this.replacedClasses.add(type)) { this.replaceJavaNativeClass(type, scope); } return type; }
8
public int[] getPixels() { return pixels; }
0
@Override public void execute(CommandSender sender, String[] arg1) { if (!CommandUtil.hasPermission(sender, PERMISSION_NODES)) { sender.sendMessage(plugin.NO_PERMISSION); return; } try { if(plugin.getUtilities().chatChannelExists(arg1[0])){ sender.sendMessage(plugin.CHANNEL_ALREADY_EXISTS); return; } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (plugin.getChatPlayer(sender.getName()).getChannelsOwned() >= plugin.maxCustomChannels && !CommandUtil.hasPermission(sender, PERMISSION_NODES_OVERRIDE)) { sender.sendMessage(plugin.CHANNEL_TOO_MANY); return; } if (arg1.length == 1) { String name = arg1[0]; plugin.getUtilities().createChannel(name, plugin.defaultCustomChannelFormat, false, sender.getName()); String chmsg = plugin.CHANNEL_CREATE_CONFIRM; chmsg = chmsg.replace("%channel", name); sender.sendMessage(chmsg); } else if (arg1.length == 2) { String name = arg1[0]; String format = arg1[1]; try { if(plugin.getUtilities().chatChannelExists(arg1[0])){ sender.sendMessage(plugin.CHANNEL_ALREADY_EXISTS); return; } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } plugin.getUtilities().createChannel(name, format, false, sender.getName()); String chmsg = plugin.CHANNEL_CREATE_CONFIRM; chmsg = chmsg.replace("%channel", name); sender.sendMessage(chmsg); } else sender.sendMessage(ChatColor.RED + "/" + plugin.create + " (channel) [format]"); }
9
public boolean save(ArrayList aguardar){ return false; }
0
@After public void tearDown() throws Exception { this.scheduler.shutdown(); }
0
public static void update() { for(Keybinds keybinds : Keybinds.values()) { keybinds.key.setHeld(keybinds.key.isPressed()); keybinds.key.update(); } }
1
public static int longestIncreasingSeq(ArrayList<Person> circus) { Collections.sort(circus); Hashtable<Person, Integer> hashtable = new Hashtable<Person, Integer>(); for (int i = 0; i < circus.size(); ++i) { Person curr = circus.get(i); if (!hashtable.containsKey(curr)) { hashtable.put(curr, 1); } int max_prev = 0; for (int j = 0; j < i; ++j) { Person prev = circus.get(j); if (prev.isOntopOf(curr) && hashtable.get(prev) > max_prev) { max_prev = hashtable.get(prev); } } hashtable.put(curr, hashtable.get(curr) + max_prev); } int max = 0; for (Person p : circus) { if (hashtable.get(p) > max) { max = hashtable.get(p); } } return max; }
7
@Override public Object getValueAt(int rowIndex, int columnIndex) { DetallePedido detalle = detalles.get(rowIndex); switch(columnIndex){ case 0 : return detalle.getIdArticulo(); case 1 : { try { return ArticuloController.buscarArticulos(detalle.getIdArticulo()).getNombre(); } catch (ClassNotFoundException | SQLException ex) { Logger.getLogger(DetalleTM.class.getName()).log(Level.SEVERE, null, ex); } } case 2 : return detalle.getCantidad(); case 3 : return detalle.getPrecio(); case 4 : return detalle.getPrecio().multiply(new BigDecimal(detalle.getCantidad())); default: return null; } }
6
private void closeChannel(){ try { if(this.fileInput != null){ this.fileInput.close(); this.fileInput = null; } if(this.fileChannel != null){ this.fileChannel.close(); this.fileChannel = null; } }catch (IOException ex) { ex.printStackTrace(); } }
3
public boolean isOpen(String direction) { switch (direction) { case "north": if (this.north[1].equals("True")) { return true; } else { return false; } case "east": if (this.east[1].equals("True")) { return true; } else { return false; } case "south": if (this.south[1].equals("True")) { return true; } else { return false; } case "west": if (this.west[1].equals("True")) { return true; } else { return false; } default: System.out.println("Valid options are: North, East, South, West!"); return false; } }
8
@Override public void startSetup(Attributes atts) { super.startSetup(atts); setEnabled(false); addActionListener(this); Outliner.documents.addTreeSelectionListener(this); Outliner.documents.addDocumentRepositoryListener(this); }
0
public void setEstrCaso(List<?> list) { for(PEstrCaso e : this._estrCaso_) { e.parent(null); } this._estrCaso_.clear(); for(Object obj_e : list) { PEstrCaso e = (PEstrCaso) obj_e; if(e.parent() != null) { e.parent().removeChild(e); } e.parent(this); this._estrCaso_.add(e); } }
4
* @param renamed_New * @param old * @return String */ public static String replaceSubstrings(String string, String renamed_New, String old) { { int stringlength = string.length(); int oldlength = old.length(); int newlength = renamed_New.length(); int nofoccurrences = 0; int oldstart = 0; int cursor = 0; int resultcursor = 0; StringBuffer result = null; while ((oldstart = Native.stringSearch(string, old, cursor)) != Stella.NULL_INTEGER) { nofoccurrences = nofoccurrences + 1; cursor = oldstart + oldlength; } if (nofoccurrences == 0) { return (string); } result = Stella.makeRawMutableString(stringlength + (nofoccurrences * (newlength - oldlength))); cursor = 0; while ((oldstart = Native.stringSearch(string, old, cursor)) != Stella.NULL_INTEGER) { { int i = Stella.NULL_INTEGER; int iter000 = cursor; int upperBound000 = oldstart - 1; for (;iter000 <= upperBound000; iter000 = iter000 + 1) { i = iter000; edu.isi.stella.javalib.Native.mutableString_nthSetter(result, (string.charAt(i)), resultcursor); resultcursor = resultcursor + 1; } } { char renamed_Char = Stella.NULL_CHARACTER; String vector000 = renamed_New; int index000 = 0; int length000 = vector000.length(); for (;index000 < length000; index000 = index000 + 1) { renamed_Char = vector000.charAt(index000); edu.isi.stella.javalib.Native.mutableString_nthSetter(result, renamed_Char, resultcursor); resultcursor = resultcursor + 1; } } cursor = oldstart + oldlength; } { int i = Stella.NULL_INTEGER; int iter001 = cursor; int upperBound001 = stringlength - 1; for (;iter001 <= upperBound001; iter001 = iter001 + 1) { i = iter001; edu.isi.stella.javalib.Native.mutableString_nthSetter(result, (string.charAt(i)), resultcursor); resultcursor = resultcursor + 1; } } return (result.toString()); } }
6
static CtClass toPrimitiveClass(char c) { CtClass type = null; switch (c) { case 'Z' : type = CtClass.booleanType; break; case 'C' : type = CtClass.charType; break; case 'B' : type = CtClass.byteType; break; case 'S' : type = CtClass.shortType; break; case 'I' : type = CtClass.intType; break; case 'J' : type = CtClass.longType; break; case 'F' : type = CtClass.floatType; break; case 'D' : type = CtClass.doubleType; break; case 'V' : type = CtClass.voidType; break; } return type; }
9