text
stringlengths
14
410k
label
int32
0
9
public void start_logging() { ++start_logging_count; }
0
public void paintShape(Graphics2D g2) { if (image != null) { Dimension dim = label.getPreferredSize(); if (dim.width > 0 && dim.height > 0) { label.setBounds(0, 0, dim.width, dim.height); g2.translate(getX(), getY()); g2.scale((image.getWidth() + 2 * xGrow) / dim.width, (image.getHeight() + 2 * yGrow) / dim.height); label.paint(g2); } } }
3
@Override public void doAction() { QuestionManager.getInstance().setQuestion(QuestionsCache.getNextQuestion()); StateManager.getInstance().setState(new QuestionLoaded()); }
0
private GenericConverter getRegisteredConverter(Class<?> sourceType, Class<?> targetType, Class<?> sourceCandidate, Class<?> targetCandidate) { ConvertersForPair convertersForPair = converters.get(new ConvertiblePair(sourceCandidate, targetCandidate)); return convertersForPair == null ? null : convertersForPair.getConverter(sourceType, targetType); }
5
public static void handleJoin(String channel) { if ( !channel.startsWith("#") ) { appendError("Nesprávná syntaxe příkazu: /join #kanál"); return; } getCurrentServerTab().getConnection().joinChannel(channel); clearInput(); }
1
public static Map<String, String> simpleCommandLineParser(String[] args) { Map<String, String> map = new HashMap<String, String>(); for (int i = 0; i <= args.length; i++) { String key = (i > 0 ? args[i-1] : null); String value = (i < args.length ? args[i] : null); if (key == null || key.startsWith("-")) { if (value != null && value.startsWith("-")) value = null; if (key != null || value != null) map.put(key, value); } } return map; }
9
public String getURI() { return uri; }
0
public static ArrayList getTotaisOpMes(String data_in, Integer gmp, String arg_prod) throws SQLException, ClassNotFoundException { ArrayList sts = new ArrayList(); Connection conPol = conMgr.getConnection("PD"); ResultSet rs; if (conPol == null) { throw new SQLException("Numero Maximo de Conexoes Atingida!"); } if(data_in.length() > 7){ data_in = data_in.substring(3); } try { call = conPol.prepareCall("{call sp_op_resumo_mes( ?, ?, ?)}"); call.setString(1, data_in); call.setInt(2, gmp); call.setString(3, arg_prod); rs = call.executeQuery(); while (rs.next()) { sts.add("<a href=consultaServ?acao=opsConsultaOp&txt_op=" + rs.getInt("op") + ">" + rs.getInt("op") + "</a> \t" + rs.getDate("data_op") + "\t" + rs.getString("nroserieini") + "\t" + rs.getString("nroseriefim") + "\t" + formatt.format(rs.getTimestamp("dt_min")) + "\t" + formatt.format(rs.getTimestamp("dt_max")) + "\t" + rs.getInt("qtd_op") + "\t" + rs.getInt("cont") + "\t" + rs.getString("item") + "\t"); } } finally { if (conPol != null) { conMgr.freeConnection("PD", conPol); } } return sts; }
4
public static void main(String[] args){ Class c = null; try{ c = Class.forName("org.jimmy.grammar.FancyToy"); //Can't work. //c = Class.forName("org.jimmy.grammar.Chap14Q1.FancyToy"); }catch(ClassNotFoundException e){ System.out.println("Can't find FancyToy."); System.exit(1); } printInfo(c); for(Class face : c.getInterfaces()){ printInfo(face); } Class up = c.getSuperclass(); Object obj = null; try{ obj = up.newInstance();//该class必须有默认的构造函数; }catch(InstantiationException e){ System.out.println("Can not instantiate"); }catch(IllegalAccessException e){ System.out.println("Can not access"); System.exit(1); } printInfo(obj.getClass()); }
4
public int isWon() { if(flaggedLocs().size()==numMines) for(Location L:flaggedLocs()) if(!L.isMined()) { won=2; return won; } else won=1; if(won==1) return won; else for(Location L:minedLocs()) if(L.isClicked()) won=0; return won; }
6
public HashMap<String,ArrayList<String>> combineBodyText(ArrayList<String> bodyPieces){ ArrayList<String> bodyText = new ArrayList<String>(); ArrayList<String> bodyPic = new ArrayList<String>(); int i=0,j,k; while(i<bodyPieces.size()){ String textStr = ""; String picStr = ""; if(!isPic(bodyPieces.get(i))) { for(j=i;j<bodyPieces.size() && !isPic(bodyPieces.get(j));j++){ textStr = textStr+bodyPieces.get(j)+"\n"; } bodyText.add(textStr); i=j; } else{ for(k = i;k<bodyPieces.size() && isPic(bodyPieces.get(k));k++){ picStr = picStr + bodyPieces.get(k)+","; } bodyPic.add(picStr); i=k; } } HashMap<String,ArrayList<String>> hashMap = new HashMap<String, ArrayList<String>>(); hashMap.put("bodyText",bodyText); hashMap.put("bodyPic",bodyPic); return hashMap; }
6
public Composite<P> setChildren(View<?>... children) { for (View<?> child : this.children) { child.setParent(null); } this.children.clear(); for (View<?> child : children) { this.children.add(child); child.setParent(this); } P ownPresentation = getPresentation(); if (ownPresentation != null) { ownPresentation.removeAllComponents(); for (View<?> child : children) { Component childPresentation = child.getPresentation(); if (childPresentation != null) { ownPresentation.addComponent(childPresentation); } } } return this; }
9
public static boolean existeCorreo(String correo) { Connection conn = null; PreparedStatement stmt = null; boolean existe = false; try { conn = model.ConexionMySQL.darConexion(); stmt = conn.prepareStatement("Select count(*) as count from usuario where correo=?"); stmt.setString(1, correo.trim()); ResultSet result = stmt.executeQuery(); while (result.next()) { existe = (Integer.parseInt(result.getString("count")) > 0) ? true : existe; } } catch (SQLException e) { //No Quiero que pase } finally { if (stmt != null) { try { stmt.close(); } catch (SQLException ex) { //Que no pasa! } } if (conn != null) { try { conn.close(); } catch (SQLException ex) { //Tampoco acá } } } return existe; }
7
public void tick() { super.tick(); if (level.game.getKeyboard().left) left = true; else left = false; if (level.game.getKeyboard().right) right = true; else right = false; if (level.game.getKeyboard().up || level.game.getKeyboard().space) { jump(); } updateAnimation(); }
4
public CheckResultMessage check13(int day) { int r1 = get(33, 5); int c1 = get(34, 5); int r2 = get(36, 5); int c2 = get(37, 5); BigDecimal b = new BigDecimal(0); if (checkVersion(file).equals("2003")) { try { in = new FileInputStream(file); hWorkbook = new HSSFWorkbook(in); b = getValue(r2 + 1 + day, c2 + 1, 9).add( getValue(r2 + 1 + day, c2 + 3, 9)).add( getValue(r2 + 1 + day, c2 + 5, 9)); if (0 != getValue(r1, c1 + 1 + day, 8).compareTo(b)) { return error("支付机构汇总报表<" + fileName + ">系统已增加银行未增加未达账项余额:" + day + "日错误"); } } catch (Exception e) { } } else { try { in = new FileInputStream(file); xWorkbook = new XSSFWorkbook(in); b = getValue1(r2 + 1 + day, c2 + 1, 9).add( getValue1(r2 + 1 + day, c2 + 3, 9)).add( getValue1(r2 + 1 + day, c2 + 5, 9)); if (0 != getValue1(r1, c1 + 1 + day, 8).compareTo(b)) { return error("支付机构汇总报表<" + fileName + ">系统已增加银行未增加未达账项余额:" + day + "日错误"); } } catch (Exception e) { } } return pass("支付机构汇总报表<" + fileName + ">系统已增加银行未增加未达账项余额:" + day + "日正确"); }
5
@Override public void setProbabilities(Double[] probabilities) throws NGramException { /* * int count = 0;// count the index of string[] probabilities if * (probabilities == null) { throw new * NGramException("ERROR: probabilities null or contains!"); } for * (Double i : probabilities) { if ((i == null) || (i > 1) || (i <= 0)) * { throw new NGramException( * "ERROR: probabilities contain at least one entry " + * "which is null , zero, negative or greater than 1.0"); } } * * count = probabilities.length; for (Double d : probabilities) { * this.probabilities[count] = d; count++; } */ // new version use the checkArray check probabilities,and use list store // the probabilities if (checkArray(probabilities) == false) { throw new NGramException( "ERROR: probabilities is null or contains at least one entry which is null , zero, negative or greater than 1.0"); } probabilitiesList.clear(); for (double d : probabilities) { probabilitiesList.add(d); } }
2
public void setRadius(double radius) { this.radius = radius; }
0
@Basic @Column(name = "discount_percent") public int getDiscountPercent() { return discountPercent; }
0
public static boolean methodNeedsEvaluatorWrapperP(MethodSlot method) { { boolean testValue000 = false; testValue000 = MethodSlot.methodMustBeEvaluableP(method); if (testValue000) { if (((BooleanWrapper)(KeyValueList.dynamicSlotValue(method.dynamicSlots, Stella.SYM_STELLA_METHOD_VARIABLE_ARGUMENTSp, Stella.FALSE_WRAPPER))).wrapperValue) { testValue000 = true; } else { if (method.methodParameterNames().length() > 5) { testValue000 = true; } else { if (method.methodReturnTypeSpecifiers().length() > 1) { testValue000 = true; } else { if (Surrogate.subtypeOfP(method.type(), Stella.SGT_STELLA_LITERAL)) { testValue000 = true; } else { { boolean foundP000 = false; { StandardObject tspec = null; Cons iter000 = method.methodParameterTypeSpecifiers().theConsList; loop000 : for (;!(iter000 == Stella.NIL); iter000 = iter000.rest) { tspec = ((StandardObject)(iter000.value)); if (Surrogate.subtypeOfP(StandardObject.typeSpecToBaseType(tspec), Stella.SGT_STELLA_LITERAL)) { foundP000 = true; break loop000; } } } testValue000 = foundP000; } } } } } } { boolean value000 = testValue000; return (value000); } } }
7
@Override public void processBroadcastMsg(Message m) { if (m instanceof PackHello) { ((PackHello) m).setHops(hops); ((PackHello) m).setMetric(metricPath); ((PackHello) m).setPaths(pathsToSink); ((PackHello) m).setSinkID(sinkID); broadcast(m); statistic.countBroadcastTree(); } if (m instanceof PackReply) { ((PackReply) m).setHops(hops); ((PackReply) m).setPath(pathsToSink); ((PackReply) m).setSenderID(this.ID); ((PackReply) m).setSinkID(sinkID); ((PackReply) m).setSendTo(nextHop); ((PackReply) m).setSendToNodes(neighborsFathes); ((PackReply) m).setMetric(metricPath); ((PackReply) m).setsBet(sBet); ((PackReply) m).setFwdID(this.ID); broadcast(m); statistic.countBroadcastTree(); } if (m instanceof PackEvent) { // a energia gasta esta implementada dentro // do broadcastMsgWithNack ((PackEvent) m).setNextHop(nextHop); broadcastMsgWithNack(m); protocol.setInAgregation(false); } }
3
private void findOuterGraph(HashMap<String, String> relevantSPARQLBlocks, int varIndex){ int charIndex = varIndex; int bracketIndex = 0; int maxBracketIndex = 0; while (true){ if (charIndex==0){ String currentLine = getCurrentLine(text, charIndex); if (addNewGraphBlockMapping(relevantSPARQLBlocks, varIndex, currentLine)==false){ if (!relevantSPARQLBlocks.containsKey("DEFAULT")){ String outerBlock = extractOuterBlock(varIndex); relevantSPARQLBlocks.put("DEFAULT", outerBlock); } } break; } if (text.charAt(charIndex)=='{'){ bracketIndex++; if (bracketIndex > maxBracketIndex){ maxBracketIndex++; String currentLine = getCurrentLine(text, charIndex); if (addNewGraphBlockMapping(relevantSPARQLBlocks, varIndex, currentLine)){ break; } } } else if (text.charAt(charIndex)=='}'){ bracketIndex--; } charIndex--; } }
8
public Object invokeImpl(Object proxy, Method method, Object[] args) throws EvalError { String methodName = method.getName(); CallStack callstack = new CallStack(namespace); /* * If equals() is not explicitly defined we must override the * default implemented by the This object protocol for scripted * object. To support XThis equals() must test for equality with the * generated proxy object, not the scripted bsh This object; * otherwise callers from outside in Java will not see a the proxy * object as equal to itself. */ BshMethod equalsMethod = null; try { equalsMethod = namespace.getMethod("equals", new Class[] { Object.class }); } catch (UtilEvalError e) {/* leave null */ } if (methodName.equals("equals") && equalsMethod == null) { Object obj = args[0]; return proxy == obj; } /* * If toString() is not explicitly defined override the default to * show the proxy interfaces. */ BshMethod toStringMethod = null; try { toStringMethod = namespace.getMethod("toString", new Class[] {}); } catch (UtilEvalError e) {/* leave null */ } if (methodName.equals("toString") && toStringMethod == null) { Class[] ints = proxy.getClass().getInterfaces(); // XThis.this refers to the enclosing class instance StringBuilder sb = new StringBuilder(This.this.toString() + "\nimplements:"); for (int i = 0; i < ints.length; i++) sb.append(" " + ints[i].getName() + ((ints.length > 1) ? "," : "")); return sb.toString(); } Class[] paramTypes = method.getParameterTypes(); return Primitive.unwrap(invokeMethod(methodName, Primitive.wrap(args, paramTypes))); }
8
@Override public void encode(OutputStream os) throws IOException { os.write(PREFIX); for (BencodeType bencodeType : list) { bencodeType.encode(os); } os.write(COMMON_POSTFIX); }
1
void write(DataOutputStream out) throws IOException { out.writeShort(accessFlags); out.writeShort(name); out.writeShort(descriptor); if (attribute == null) out.writeShort(0); else { out.writeShort(attribute.size()); AttributeInfo.writeAll(attribute, out); } }
1
public static void main(String[] args) { // TODO Auto-generated method stub int array[]= new int[args.length]; for(int k = 0; k < array.length; k++){ array[k]=Integer.parseInt(args[k]); } int array2 [] = {180,15,70,9,7}; System.out.println(Arrays.toString(array2)); // sort(array); sort(array2); System.out.println(Arrays.toString(array2)); }
1
public void setSurrenderPending(boolean pending) { if (pending) { surrenderButton.setText(SURRENDER_BUTTON_CONFIRM_TEXT); surrenderButton.setActionCommand(SURRENDER_BUTTON_CONFIRM_TEXT); } else { surrenderButton.setText(SURRENDER_BUTTON_TEXT); surrenderButton.setActionCommand(SURRENDER_BUTTON_TEXT); } }
1
private JPanel createRoleAssignmentPanel(Person person) { JPanel roleAssignmentPanel = new JPanel(); TitledBorder titledBorder = BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Zugewiesene Rollen"); roleAssignmentPanel.setBorder(titledBorder); double size[][] = { { 20, TableLayout.FILL }, { TableLayout.PREFERRED } }; TableLayout layout = new TableLayout(size); roleAssignmentPanel.setLayout(layout); if (isPersonAssignedAnyProduction(person)) { int rowCounter = 0; for (Production production : ShowGoDAO.getShowGo().getProductions()) { if (roleAssignedInProduction(production, person)) { log.debug("role assigned in: " + production); layout.insertRow(rowCounter, TableLayout.PREFERRED); roleAssignmentPanel.add(new JLabel("Inszenierung \"" + production.getName() + "\":"), "0," + rowCounter + ",1," + rowCounter); rowCounter++; for (Role role : production.getPlay().getRoles()) { if (role.getCast() != null) { if (role.getCast().contains(person)) { layout.insertRow(rowCounter, TableLayout.PREFERRED); roleAssignmentPanel.add(new JLabel("\t" + role.getName()), "1," + rowCounter); rowCounter++; } } } for (Role role : production.getNonActorRoles()) { if (role.getCast() != null) { if (role.getCast().contains(person)) { layout.insertRow(rowCounter, TableLayout.PREFERRED); roleAssignmentPanel.add(new JLabel("\t" + role.getName()), "1," + rowCounter); rowCounter++; } } } } } } else { log.debug("not assigned to any roles"); roleAssignmentPanel.add(new JLabel(person.getName() + " ist derzeit keinen Rollen zugewiesen."), "0,0,1,0"); } return roleAssignmentPanel; }
9
private LinkGene crossoverLinkGenes(LinkGene a, LinkGene b){ double weightA = a.getWeight(); double weightB = b.getWeight(); long weightALong = Double.doubleToRawLongBits(weightA); long weightBLong = Double.doubleToRawLongBits(weightB); long mask = -1L; // all bits set to 1 double newWeight; do{ int crossOverPoint = randInt(0, Long.SIZE); long combined; // treat special cases because of modulo Long.SIZE of second parameter of shifting operations if (crossOverPoint == 0) { combined = weightBLong; } else if (crossOverPoint == Long.SIZE) { combined = weightALong; } else { combined = (weightALong & (mask << (Long.SIZE - crossOverPoint))) | (weightBLong & (mask >>> crossOverPoint)); } newWeight = Double.longBitsToDouble(combined); } while(newWeight == Double.NaN || newWeight == Double.POSITIVE_INFINITY || newWeight == Double.NEGATIVE_INFINITY); boolean newActivation; if(a.isActivated() == b.isActivated()){ newActivation = a.isActivated(); }else { if(Math.random() > 0.5){ newActivation = a.isActivated(); } else { newActivation = b.isActivated(); } } return new LinkGene(a.getStartLayer(),a.getStartNode(),a.getEndNode(),newWeight, newActivation); }
7
@Override public void documentAdded(DocumentRepositoryEvent e) {}
0
@Override public Banker getBank(String chain, String areaNameOrBranch) { for (final Banker B : bankList) { if((B.bankChain().equalsIgnoreCase(chain)) &&(B.bankChain().equalsIgnoreCase(areaNameOrBranch))) return B; } final Area A=findArea(areaNameOrBranch); if(A==null) return null; for (final Banker B : bankList) { if((B.bankChain().equalsIgnoreCase(chain)) &&(getStartArea(B)==A)) return B; } return null; }
7
public static void main(String[] args) throws FileNotFoundException { File f = new File("src/jobs.txt"); Scanner sr = new Scanner(f); sr.next(); int i = 0; for (i = 0; i < 10000; i++) { jobs[i][0] = sr.nextInt(); jobs[i][1] = sr.nextInt(); jobs[i][2] = jobs[i][0] / jobs[i][1]; } Sortingbydifference(); // Sortingbywieghtdividedbylength(); for (i = 0; i < 1000; i++) { System.out.print(jobs[i][0] + " "); System.out.print(jobs[i][1] + " "); System.out.print(jobs[i][2] + " "); System.out.print("\n"); } int time = 0; long wieghtedtime = 0; for (i = 0; i < 10000; i++) { time = (int) ((int) time + jobs[i][1]); wieghtedtime = (long) ((long) wieghtedtime + time * jobs[i][0]); } System.out.print(wieghtedtime); }
3
public int getDestinationStop() { return this._destinationStop; }
0
public void setShips() { for(int i = 0; i < players.size(); i++) { ShipPanel s = players.get(i).getShip(); // Set border to player color if(players.get(i).getNumber() == 1) s.setBorder(BorderFactory.createLineBorder(GameBoard.PLAYER1)); else if(players.get(i).getNumber() == 2) s.setBorder(BorderFactory.createLineBorder(GameBoard.PLAYER2)); else if(players.get(i).getNumber() == 3) s.setBorder(BorderFactory.createLineBorder(GameBoard.PLAYER3)); else s.setBorder(BorderFactory.createLineBorder(GameBoard.PLAYER4)); mother.add(s, new Integer(2), 0); movePlayer(players.get(i).getNumber(), 0, false, false); } }
4
public void visitFrame(final int type, final int nLocal, final Object[] local, final int nStack, final Object[] stack) { buf.setLength(0); buf.append(ltab); buf.append("FRAME "); switch (type) { case Opcodes.F_NEW: case Opcodes.F_FULL: buf.append("FULL ["); appendFrameTypes(nLocal, local); buf.append("] ["); appendFrameTypes(nStack, stack); buf.append(']'); break; case Opcodes.F_APPEND: buf.append("APPEND ["); appendFrameTypes(nLocal, local); buf.append(']'); break; case Opcodes.F_CHOP: buf.append("CHOP ").append(nLocal); break; case Opcodes.F_SAME: buf.append("SAME"); break; case Opcodes.F_SAME1: buf.append("SAME1 "); appendFrameTypes(1, stack); break; } buf.append('\n'); text.add(buf.toString()); if (mv != null) { mv.visitFrame(type, nLocal, local, nStack, stack); } }
7
public void testStream () throws IOException { final int largeDataSize = 12345; final Server server = new Server(16384, 8192); server.getKryo().setRegistrationRequired(false); startEndPoint(server); server.bind(tcpPort, udpPort); server.addListener(new Listener() { public void connected (Connection connection) { ByteArrayOutputStream output = new ByteArrayOutputStream(largeDataSize); for (int i = 0; i < largeDataSize; i++) output.write(i); ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray()); // Send data in 512 byte chunks. connection.addListener(new InputStreamSender(input, 512) { protected void start () { // Normally would send an object so the receiving side knows how to handle the chunks we are about to send. System.out.println("starting"); } protected Object next (byte[] bytes) { System.out.println("sending " + bytes.length); return bytes; // Normally would wrap the byte[] with an object so the receiving side knows how to handle it. } }); } }); // ---- final Client client = new Client(16384, 8192); client.getKryo().setRegistrationRequired(false); startEndPoint(client); client.addListener(new Listener() { int total; public void received (Connection connection, Object object) { if (object instanceof byte[]) { int length = ((byte[])object).length; System.out.println("received " + length); total += length; if (total == largeDataSize) { success = true; stopEndPoints(); } } } }); client.connect(5000, host, tcpPort, udpPort); waitForThreads(5000); if (!success) fail(); }
4
@Override public void setProbability(double[] p, Map<String,Integer> stateToIndex) throws IllegalArgumentException { if( p == null) throw new IllegalArgumentException("Error: null probability distribution"); double sum = 0.0; for( int i = 0; i < p.length; ++i) { sum += p[i]; if( Double.isNaN(p[i])) throw new IllegalArgumentException("Error: NaN probability value"); if(p[i] < 0) throw new IllegalArgumentException("Error: probability value smaller then 0"); if(p[i] > 1) throw new IllegalArgumentException("Error: probability value bigger then 1"); } if( sum + 0.0001 < 1.0 || sum - 0.0001 > 1.0) throw new IllegalArgumentException("Error: probability distribution doesn't sum 1"); this.pDistr = p; this.stateToIndex = stateToIndex; }
7
public void removeFrame( JInternalFrame jif ) { // if( jif.getClass().toString().equalsIgnoreCase( "class ImageFrame" ) //remove ImageFrame // || jif.getClass().toString().equalsIgnoreCase( "class HistogramFrame" ) ) //remove histogramFrame if( jif instanceof ImageFrame || jif instanceof HistogramFrame ) { for(int loop=0; loop < frame_list.size(); loop++) { ImageFrame j = (ImageFrame) frame_list.get(loop); if(jif.getTitle().equalsIgnoreCase( j.getTitle() ) ) { //get matching histogramFrame HistogramFrame hf = (HistogramFrame) histFrame_list.get(loop); showInfoFrame( false ); //close info frame for this window (if open) histFrame_list.remove( loop ); //remove HistogramFrame from arrayList hf.dispose(); frame_list.remove( loop ); //remove ImageFrame from arrayList } } updateDocTitles(); } else // JIPTInfoFrame info_frame.setEnabled( false ); //just hide Info Frame //disable AtLeastOneFrameOpen actions if( this.frame_list.isEmpty() ) main_frame.menu_bar.disableAtLeastOneFrameOpenActions(); }
5
private Block parseForRun() throws InterpreterException { int i = 0; Block first = null; Block last = null; while (i < code_.length) { String copy[] = new String[code_.length - i]; System.arraycopy(code_, i, copy, 0, copy.length); ReturnStruct rs = Parser.parseLine(this, code_[i], copy, getLine() + i + 1); Block b = rs.block; i += rs.lines; if (b instanceof ELSEBlock) { rs.block.setLine(getLine() + 1 + i); this.setElse(b); } if (b != null) { if (first == null) { first = b; last = b; } else { last.setNext(b); last = b; } } } last.setNext(super.next()); return first; }
4
public byte convertBitsToValue(byte org,int startBit, int endBit, boolean value){ System.out.println("StartBit="+startBit+"/endBit="+endBit); int mask1 = (255 >> startBit); //for above example, mask 1 = 00000011; System.out.println("mask1="+String.format("%8s", Integer.toBinaryString(mask1)).replace(' ', '0')); int mask2 = (255 >> (endBit+1)); //for above example, mask 2 = 00111111; System.out.println("mask2="+String.format("%8s", Integer.toBinaryString(mask2)).replace(' ', '0')); int mask = (mask1 ^ mask2); // mask = 00111100; System.out.println("mask="+String.format("%8s", Integer.toBinaryString(mask)).replace(' ', '0')); //!!!!! when mask is larger than 127, there is problem with result, bigger than 8 bits! byte fmask = (byte)(mask); System.out.println("fmask="+String.format("%8s", Integer.toBinaryString(fmask & 0xff)).replace(' ', '0')); if(value == true){ //convert from startBit to endBit to 1; return (byte)(org | (fmask & 0xff)); }else { return (byte)(org & ~ mask); } }
1
@SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { mainContainer = new javax.swing.JPanel(); topSubContainer = new javax.swing.JPanel(); jButton3 = new javax.swing.JButton(); jButton10 = new javax.swing.JButton(); StepCount = new javax.swing.JLabel(); GemCount = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); bottomSubContainer = new javax.swing.JPanel(); middleContainer = new javax.swing.JPanel(); leftContainer = new javax.swing.JPanel(); buttonPanel = new javax.swing.JPanel(); jButton4 = new javax.swing.JButton(); jButton5 = new javax.swing.JButton(); jButton6 = new javax.swing.JButton(); jButton8 = new javax.swing.JButton(); jButton9 = new javax.swing.JButton(); manualPanel = new javax.swing.JPanel(); Slowdown = new javax.swing.JButton(); Pause = new javax.swing.JButton(); Speedup = new javax.swing.JButton(); speedCounter = new javax.swing.JTextField(); Stop = new javax.swing.JButton(); Reset = new javax.swing.JButton(); logPane = new javax.swing.JScrollPane(); logText = new javax.swing.JTextArea(); logClear = new javax.swing.JButton(); blankPanel = new javax.swing.JPanel(); rightContainer = new javax.swing.JPanel(); world = new karel.World(); jMenuBar1 = new javax.swing.JMenuBar(); jMenu1 = new javax.swing.JMenu(); jMenuItem2 = new javax.swing.JMenuItem(); jMenuItem1 = new javax.swing.JMenuItem(); jMenu3 = new javax.swing.JMenu(); jMenuItem8 = new javax.swing.JMenuItem(); jMenuItem6 = new javax.swing.JMenuItem(); jMenuItem5 = new javax.swing.JMenuItem(); jMenuItem7 = new javax.swing.JMenuItem(); jMenu2 = new javax.swing.JMenu(); jMenuItem3 = new javax.swing.JMenuItem(); jMenuItem4 = new javax.swing.JMenuItem(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setPreferredSize(new java.awt.Dimension(990, 552)); setResizable(false); mainContainer.setBackground(new java.awt.Color(51, 0, 0)); mainContainer.setLayout(new java.awt.BorderLayout()); topSubContainer.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(153, 153, 153))); topSubContainer.setFocusable(false); topSubContainer.setMaximumSize(new java.awt.Dimension(32767, 28)); topSubContainer.setMinimumSize(new java.awt.Dimension(100, 28)); topSubContainer.setPreferredSize(new java.awt.Dimension(733, 28)); jButton3.setText("Button Mode"); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); jButton10.setText("Programmer Mode"); jButton10.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton10ActionPerformed(evt); } }); StepCount.setText("0"); GemCount.setText("0"); jLabel2.setText("Moves:"); jLabel3.setText("Gems:"); javax.swing.GroupLayout topSubContainerLayout = new javax.swing.GroupLayout(topSubContainer); topSubContainer.setLayout(topSubContainerLayout); topSubContainerLayout.setHorizontalGroup( topSubContainerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(topSubContainerLayout.createSequentialGroup() .addContainerGap() .addComponent(jButton3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton10) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 611, Short.MAX_VALUE) .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(StepCount) .addGap(13, 13, 13) .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(GemCount) .addGap(70, 70, 70)) ); topSubContainerLayout.setVerticalGroup( topSubContainerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(topSubContainerLayout.createSequentialGroup() .addGroup(topSubContainerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton3) .addComponent(jButton10) .addComponent(StepCount) .addComponent(GemCount) .addComponent(jLabel2) .addComponent(jLabel3)) .addGap(0, 3, Short.MAX_VALUE)) ); mainContainer.add(topSubContainer, java.awt.BorderLayout.PAGE_START); bottomSubContainer.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(153, 153, 153))); bottomSubContainer.setMaximumSize(new java.awt.Dimension(32767, 30)); bottomSubContainer.setMinimumSize(new java.awt.Dimension(100, 35)); javax.swing.GroupLayout bottomSubContainerLayout = new javax.swing.GroupLayout(bottomSubContainer); bottomSubContainer.setLayout(bottomSubContainerLayout); bottomSubContainerLayout.setHorizontalGroup( bottomSubContainerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 1019, Short.MAX_VALUE) ); bottomSubContainerLayout.setVerticalGroup( bottomSubContainerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 36, Short.MAX_VALUE) ); mainContainer.add(bottomSubContainer, java.awt.BorderLayout.PAGE_END); middleContainer.setBackground(new java.awt.Color(153, 153, 153)); middleContainer.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(153, 153, 153))); middleContainer.setMaximumSize(new java.awt.Dimension(2147483647, 438)); middleContainer.setPreferredSize(new java.awt.Dimension(975, 436)); middleContainer.setLayout(new java.awt.BorderLayout()); leftContainer.setMaximumSize(new java.awt.Dimension(430, 32767)); leftContainer.setMinimumSize(new java.awt.Dimension(430, 100)); leftContainer.setPreferredSize(new java.awt.Dimension(395, 436)); leftContainer.setLayout(new java.awt.CardLayout()); buttonPanel.setVisible(false); buttonPanel.setPreferredSize(new java.awt.Dimension(395, 440)); jButton4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton4ActionPerformed(evt); } }); jButton5.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton5ActionPerformed(evt); } }); jButton6.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton6ActionPerformed(evt); } }); jButton8.setText("Get"); jButton8.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton8ActionPerformed(evt); } }); jButton9.setText("Put"); jButton9.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton9ActionPerformed(evt); } }); javax.swing.GroupLayout buttonPanelLayout = new javax.swing.GroupLayout(buttonPanel); buttonPanel.setLayout(buttonPanelLayout); buttonPanelLayout.setHorizontalGroup( buttonPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(buttonPanelLayout.createSequentialGroup() .addGap(84, 84, 84) .addGroup(buttonPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) .addComponent(jButton4) .addGroup(buttonPanelLayout.createSequentialGroup() .addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(55, 55, 55) .addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(buttonPanelLayout.createSequentialGroup() .addComponent(jButton8) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton9))) .addContainerGap(106, Short.MAX_VALUE)) ); buttonPanelLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jButton5, jButton6, jButton8, jButton9}); buttonPanelLayout.setVerticalGroup( buttonPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(buttonPanelLayout.createSequentialGroup() .addGap(100, 100, 100) .addGroup(buttonPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(buttonPanelLayout.createSequentialGroup() .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(39, 39, 39)) .addComponent(jButton6, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton5, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(buttonPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton8) .addComponent(jButton9)) .addContainerGap(216, Short.MAX_VALUE)) ); leftContainer.add(buttonPanel, "card2"); Slowdown.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { Slowdown(evt); } }); Pause.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { Pause(evt); } }); Speedup.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { Speedup(evt); } }); speedCounter.setBackground(new java.awt.Color(204, 204, 204)); speedCounter.setFont(new java.awt.Font("Tahoma", 0, 16)); // NOI18N speedCounter.setText("Speed: " + currSpeed); Stop.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { Stop(evt); } }); Reset.setText("Reset"); Reset.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { Reset(evt); } }); logText.setBackground(new java.awt.Color(0, 0, 0)); logText.setColumns(20); logText.setForeground(new java.awt.Color(0, 255, 0)); logText.setRows(5); logText.setCaretColor(new java.awt.Color(255, 255, 255)); logText.setDisabledTextColor(new java.awt.Color(0, 255, 0)); logText.setSelectionColor(new java.awt.Color(255, 255, 255)); logPane.setViewportView(logText); logClear.setText("clear"); logClear.setActionCommand("logClear"); logClear.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { logClear(evt); } }); javax.swing.GroupLayout manualPanelLayout = new javax.swing.GroupLayout(manualPanel); manualPanel.setLayout(manualPanelLayout); manualPanelLayout.setHorizontalGroup( manualPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(manualPanelLayout.createSequentialGroup() .addGroup(manualPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(manualPanelLayout.createSequentialGroup() .addGap(124, 124, 124) .addGroup(manualPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(Reset, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(speedCounter, javax.swing.GroupLayout.DEFAULT_SIZE, 118, Short.MAX_VALUE))) .addGroup(manualPanelLayout.createSequentialGroup() .addGap(42, 42, 42) .addComponent(Slowdown, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(29, 29, 29) .addComponent(Stop, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(Pause, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(26, 26, 26) .addComponent(Speedup, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(68, Short.MAX_VALUE)) .addComponent(logPane, javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, manualPanelLayout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(logClear, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18)) ); manualPanelLayout.setVerticalGroup( manualPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(manualPanelLayout.createSequentialGroup() .addComponent(Reset, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(4, 4, 4) .addComponent(speedCounter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(manualPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(Slowdown, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Stop, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Pause, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Speedup, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(logClear) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(logPane, javax.swing.GroupLayout.PREFERRED_SIZE, 265, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(43, 43, 43)) ); logClear.getAccessibleContext().setAccessibleName("logClear"); leftContainer.add(manualPanel, "card3"); javax.swing.GroupLayout blankPanelLayout = new javax.swing.GroupLayout(blankPanel); blankPanel.setLayout(blankPanelLayout); blankPanelLayout.setHorizontalGroup( blankPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 395, Short.MAX_VALUE) ); blankPanelLayout.setVerticalGroup( blankPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 464, Short.MAX_VALUE) ); leftContainer.add(blankPanel, "card4"); middleContainer.add(leftContainer, java.awt.BorderLayout.LINE_START); rightContainer.setMinimumSize(new java.awt.Dimension(589, 100)); rightContainer.setPreferredSize(new java.awt.Dimension(589, 469)); rightContainer.setLayout(new java.awt.GridLayout(1, 0)); world.setMaximumSize(new java.awt.Dimension(589, 475)); world.setPreferredSize(new java.awt.Dimension(589, 465)); javax.swing.GroupLayout worldLayout = new javax.swing.GroupLayout(world); world.setLayout(worldLayout); worldLayout.setHorizontalGroup( worldLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 624, Short.MAX_VALUE) ); worldLayout.setVerticalGroup( worldLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 464, Short.MAX_VALUE) ); rightContainer.add(world); middleContainer.add(rightContainer, java.awt.BorderLayout.CENTER); mainContainer.add(middleContainer, java.awt.BorderLayout.CENTER); jMenu1.setText("File"); jMenuItem2.setText("Open New Map From File"); jMenuItem2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem2ActionPerformed(evt); } }); jMenu1.add(jMenuItem2); jMenuItem1.setText("Reset Current Map"); jMenuItem1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem1ActionPerformed(evt); } }); jMenu1.add(jMenuItem1); jMenuBar1.add(jMenu1); jMenu3.setText("Themes"); jMenuItem8.setText("Link to the Past"); jMenuItem8.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem8ActionPerformed(evt); } }); jMenu3.add(jMenuItem8); jMenuItem6.setText("Elements of Zelda"); jMenuItem6.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem6ActionPerformed(evt); } }); jMenu3.add(jMenuItem6); jMenuItem5.setText("MegaMan"); jMenuItem5.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem5ActionPerformed(evt); } }); jMenu3.add(jMenuItem5); jMenuItem7.setText("Princess Peach"); jMenuItem7.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem7ActionPerformed(evt); } }); jMenu3.add(jMenuItem7); jMenuBar1.add(jMenu3); jMenu2.setText("Help"); jMenuItem3.setText("Open Help File (.txt)"); jMenuItem3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem3ActionPerformed(evt); } }); jMenu2.add(jMenuItem3); jMenuItem4.setText("Open Help File (.html)"); jMenuItem4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem4ActionPerformed(evt); } }); jMenu2.add(jMenuItem4); jMenuBar1.add(jMenu2); setJMenuBar(jMenuBar1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(mainContainer, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(mainContainer, javax.swing.GroupLayout.DEFAULT_SIZE, 529, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents
0
@Override public ClienteBean get(ClienteBean oClienteBean) throws Exception { if (oClienteBean.getId() > 0) { try { oMysql.conexion(enumTipoConexion); if (!oMysql.existsOne("cliente", oClienteBean.getId())) { oClienteBean.setId(0); } else { Class yourClass = ClienteBean.class; for (Method method : yourClass.getMethods()) { if (!method.getName().substring(3).equalsIgnoreCase("id")) { if (method.getName().substring(0, 3).equalsIgnoreCase("set")) { method.invoke(oClienteBean, oMysql.getOne("cliente", method.getName().substring(3).toLowerCase(Locale.ENGLISH), oClienteBean.getId())); } } } // oClienteBean.setNombre(oMysql.getOne("cliente", "nombre", oClienteBean.getId())); // oClienteBean.setApe1(oMysql.getOne("cliente", "ape1", oClienteBean.getId())); // oClienteBean.setApe2(oMysql.getOne("cliente", "ape2", oClienteBean.getId())); // oClienteBean.setEmail(oMysql.getOne("cliente", "email", oClienteBean.getId())); } } catch (Exception e) { throw new Exception("ClienteDao.getCliente: Error: " + e.getMessage()); } finally { oMysql.desconexion(); } } else { oClienteBean.setId(0); } return oClienteBean; }
6
@Test public void testAsteroidStartingVelocityY() { for (int i = 0; i < 20; i++) { p.spawnAsteroids(); } for (Asteroid a : p.getAsteroids()) { if (a.getVelY() > -0.5 && a.getVelY() < 0.5) { assertTrue(false); } if (a.getVelY() > 2.5) { assertTrue(false); } if (a.getVelY() < -2.5) { assertTrue(false); } } }
6
@EventHandler(priority = EventPriority.NORMAL) public void onASyncOnPlayerChatEvent(AsyncPlayerChatEvent event) { Player player = event.getPlayer(); PlayerFile playerFile = new PlayerFile(player.getName()); if (playerFile.muteMuted) { String finalTime = (playerFile.muteLength.equals(0) ? AdminEye.messages .getFile().getString("normal.permanently") : ""); if (playerFile.muteLength != 0) { int time = (int) Calendar.getInstance().getTimeInMillis(); if (time >= playerFile.muteLength) { playerFile.muteMuted = false; playerFile.save(); AdminEye.broadcastAdminEyeMessage("#", "unmuted", "unmuted", "playernames", player.getName() + "%N, "); return; } int days = 0; int hours = 0; int minutes = 0; int seconds = 0; days = (playerFile.muteLength - time) / 1000 / 60 / 60 / 24; hours = ((playerFile.muteLength - time) / 1000 / 60 / 60) - (days * 24); minutes = ((playerFile.muteLength - time) / 1000 / 60) - (hours * 60) - (days * 24 * 60); seconds = ((playerFile.muteLength - time) / 1000) - (minutes * 60) - (hours * 60 * 60) - (days * 24 * 60 * 60); if (days != 0) { finalTime += " %A" + days + AdminEye.messages.getFile().getString( "normal.days"); } if (hours != 0) { finalTime += " %A" + hours + AdminEye.messages.getFile().getString( "normal.hours"); } if (minutes != 0) { finalTime += " %A" + minutes + AdminEye.messages.getFile().getString( "normal.minutes"); } if (seconds != 0) { finalTime += " %A" + seconds + AdminEye.messages.getFile().getString( "normal.seconds"); } } StefsAPI.MessageHandler.buildMessage().addSender(player.getName()) .setMessage("error.muted", AdminEye.messages) .changeVariable("time", finalTime).build(); event.setCancelled(true); } }
8
public void draw(GOut og) { GOut g = og.reclip(tlo, wsz); Coord bgc = new Coord(); for (bgc.y = 3; bgc.y < wsz.y - 6; bgc.y += bg.sz().y) { for (bgc.x = 3; bgc.x < wsz.x - 6; bgc.x += bg.sz().x) g.image(bg, bgc, new Coord(3, 3), wsz.add(new Coord(-6, -6))); } cdraw(og.reclip(xlate(Coord.z, true), sz)); wbox.draw(g, Coord.z, wsz); if (cap != null && draw_cap) { GOut cg = og.reclip(new Coord(0, -7), sz.add(0, 7)); int w = cap.tex().sz().x; int x0 = (folded) ? (mrgn.x + (w / 2)) : (sz.x / 2) - (w / 2); cg.image(cl, new Coord(x0 - cl.sz().x, 0)); cg.image(cm, new Coord(x0, 0), new Coord(w, cm.sz().y)); cg.image(cr, new Coord(x0 + w, 0)); cg.image(cap.tex(), new Coord(x0, 0)); } super.draw(og); }
5
public boolean retrieveWords(File language) { try { Scanner sc = new Scanner(language, "UTF-8"); if (!isValidLanguageFile(sc)) return false; words.clear(); while (sc.hasNextLine()) mapWord(sc.nextLine()); sc.close(); } catch (FileNotFoundException e) { return false; } return true; }
3
public void setGenre(Genre genre) { this.genre = genre; }
0
protected boolean causesCheck(PossibleTile pt, Board b){ Board bClone = b.clone(); bClone.removePiece(pt.getOriginalPiece()); Piece newPiece = pt.getOriginalPiece().clone(); newPiece.setX(pt.getX()); newPiece.setY(pt.getY()); bClone.addPiece(newPiece); if (pt.hasPieceToRemove()) { bClone.removePiece(pt.getRemovePiece()); } King k = null; for (Piece p : bClone.getPieces()) { if ( p.isWhite() == pt.getOriginalPiece().isWhite() && p instanceof King ) { k = (King) p; break; } } for (Piece p : bClone.getPieces()) { if(p.isWhite() != pt.getOriginalPiece().isWhite()) { for(PossibleTile move : p.getLazyTiles(bClone)) { if (checkSameSpace(k, move)) { return true; } } } } return false; }
8
@Override public void update(Observable board, Object o) { if (o instanceof NotifyReveal){ System.out.println("********"); } else if(o instanceof NotifyFlagged){ System.out.println("********"); } else if(o instanceof NotifyDoubted){ System.out.println("********"); } else if(o instanceof NotifyUnclicked){ System.out.println("********"); } else if(o instanceof NotifyGG) { System.out.println("********"); } else if(o instanceof NotifyRestart){ System.out.println("********"); } else if(o instanceof NotifyWin){ System.out.println("********"); } else if(o instanceof NotifyTimerChange){ System.out.println("********"); } }
8
public static double squaredMagnitude(List<Double> point) { double sum = 0; int size = point.size(); for (int i = 0; i < size; i++) { double val = point.get(i); sum += val * val; } return sum; }
1
public static double svm_predict_probability(svm_model model, svm_node[] x, double[] prob_estimates) { if ((model.param.svm_type == svm_parameter.C_SVC || model.param.svm_type == svm_parameter.NU_SVC) && model.probA!=null && model.probB!=null) { int i; int nr_class = model.nr_class; double[] dec_values = new double[nr_class*(nr_class-1)/2]; // svm_predict_values(model, x, dec_values); double min_prob=1e-7; double[][] pairwise_prob=new double[nr_class][nr_class]; int k=0; for(i=0;i<nr_class;i++) for(int j=i+1;j<nr_class;j++) { pairwise_prob[i][j]=Math.min(Math.max(sigmoid_predict(dec_values[k],model.probA[k],model.probB[k]),min_prob),1-min_prob); pairwise_prob[j][i]=1-pairwise_prob[i][j]; k++; } multiclass_probability(nr_class,pairwise_prob,prob_estimates); int prob_max_idx = 0; for(i=1;i<nr_class;i++) if(prob_estimates[i] > prob_estimates[prob_max_idx]) prob_max_idx = i; return model.label[prob_max_idx]; } else return svm_predict(model, x); }
8
static void setZeroMatrix( int[][] matrix, int n) { boolean[][] checker = new boolean[2][n]; for ( int i = 0; i < n; ++i) { checker[0][i] = false; checker[1][i] = false; } for ( int i = 0; i < n; ++i) { for ( int j = 0; j < n; ++j) { if(matrix[i][j] == 0 ) { checker[0][i] = true; checker[1][j] = true; } } } for ( int i = 0; i < n; ++i) { for ( int j = 0; j < n; ++j) { if( checker[0][i] == true || checker[1][j] == true ) { matrix[i][j] = 0; } } } }
8
public void run(){ try { InputStream inputStream = loginSocket.getInputStream(); ObjectInputStream objectInputStream = new ObjectInputStream(inputStream); OutputStream outputStream = loginSocket.getOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream); String order = (String)objectInputStream.readObject(); switch(order){ case "VERIFY_LOGIN": User user = (User) objectInputStream.readObject(); sDBM.verifyUser(user); objectOutputStream.writeObject(user); objectOutputStream.flush(); user.setLastLogin(new Date()); sDBM.updateUser(user); break; case "CHECK_UNIQUE_NICKNAME": String nickname = objectInputStream.readObject().toString(); objectOutputStream.writeBoolean(sDBM.checkUniqueNickname(nickname)); objectOutputStream.flush(); break; case "UPDATE_USER": sDBM.updateUser((User)objectInputStream.readObject()); break; case "GET_DATE": objectOutputStream.writeObject(new Date()); objectOutputStream.flush(); break; default: break; } loginSocket.close(); } catch (Exception e) { e.printStackTrace(); } }
5
void run() { BufferedReader reader = new BufferedReader(new InputStreamReader( System.in)); try { // 1. creating a socket to connect to the server requestSocket = new Socket("localhost", 2004); System.out.println("Connected to localhost in port 2004"); // 2. get Input and Output streams out = new ObjectOutputStream(requestSocket.getOutputStream()); out.flush(); in = new ObjectInputStream(requestSocket.getInputStream()); // 3: Communicating with the server do { // message = (String) in.readObject(); // System.out.println("server>" + message); sendMessage(reader.readLine()); } while (true); } catch (UnknownHostException unknownHost) { System.err.println("You are trying to connect to an unknown host!"); } catch (IOException ioException) { ioException.printStackTrace(); } finally { // 4: Closing connection try { in.close(); out.close(); requestSocket.close(); } catch (IOException ioException) { ioException.printStackTrace(); } } }
4
public void paint(Graphics2D g,boolean draw,boolean fill){ if (calcularVar) { calcular(); calcularVar = false; } if (draw && !fill) { g.draw(path); }else if(fill && !draw){ g.fill(path); }else if(draw && fill){ g.draw(path); g.fill(path); } }
7
public static Set<Component> getFocusableComponents(Component currentFocusOwner) { HashSet<Component> set = new HashSet<Component>(); set.add(currentFocusOwner); Container rootAncestor = currentFocusOwner.getFocusCycleRootAncestor(); Component comp = currentFocusOwner; while ((rootAncestor != null) && !(rootAncestor.isShowing() && rootAncestor.isFocusable() && rootAncestor.isEnabled())) { comp = rootAncestor; rootAncestor = comp.getFocusCycleRootAncestor(); } if (rootAncestor != null) { FocusTraversalPolicy policy = rootAncestor.getFocusTraversalPolicy(); Component toFocus = policy.getComponentAfter(rootAncestor, comp); while ((toFocus != null) && (set.contains(toFocus) == false)) { set.add(toFocus); toFocus = policy.getComponentAfter(rootAncestor, toFocus); } toFocus = policy.getComponentBefore(rootAncestor, comp); while ((toFocus != null) && (set.contains(toFocus) == false)) { set.add(toFocus); toFocus = policy.getComponentBefore(rootAncestor, toFocus); } } return set; }
9
public void merge(EasyPostResource obj, EasyPostResource update) { if (!obj.getClass().isAssignableFrom(update.getClass())) { return; } Method[] methods = obj.getClass().getMethods(); for (Method fromMethod: methods) { if (fromMethod.getDeclaringClass().equals(obj.getClass()) && fromMethod.getName().startsWith("get")) { String fromName = fromMethod.getName(); String toName = fromName.replace("get", "set"); try { Object value = fromMethod.invoke(update, (Object[]) null); if (value != null) { Method toMethod = obj.getClass().getMethod(toName, fromMethod.getReturnType()); toMethod.invoke(obj, value); } } catch (Exception e) { e.printStackTrace(); } } } }
6
private Field getField(Object object, String name, Boolean read) throws NullPointerException, IllegalArgumentException, IllegalAccessException, NoSuchFieldException { Field field = null; for(Class<?> c = object.getClass(); c != null; c = c.getSuperclass()) { for(Field f : c.getDeclaredFields()){ if(f.getName().equals(name) && !Modifier.isStatic(f.getModifiers())) { f.setAccessible(true); field = f; } } } if(field == null) { throw new NoSuchFieldException("No such field."); } else if(field.get(object) == null && read == true) { throw new NullPointerException("Null field value."); } return field; }
8
private static void export(File file, ResultSetReference ref, boolean withHeader) throws IOException, SQLException { Exporter exporter = Exporter.getExporter(file); try { ResultSet rs = ref.getResultSet(); ColumnOrder order = ref.getOrder(); boolean needOrderChange = order.size() > 0; int columnCount; List<String> header = new ArrayList<String>(); if (needOrderChange) { columnCount = order.size(); for (int i = 0; i < columnCount; i++) { header.add(order.getName(i)); } } else { ResultSetMetaData m = rs.getMetaData(); columnCount = m.getColumnCount(); for (int i = 0; i < columnCount; i++) { header.add(m.getColumnName(i + 1)); } } if (withHeader) { exporter.addHeader(header.toArray()); } int count = 0; while (rs.next()) { ++count; Object[] row = new Object[columnCount]; for (int i = 0; i < columnCount; i++) { int index = (needOrderChange) ? order.getOrder(i) : i + 1; row[i] = rs.getObject(index); } exporter.addRow(row); } ref.setRecordCount(count); } finally { exporter.close(); } }
7
public int init(BinarySearchTree<String,String> tree) throws IndexOutOfBoundsException, IOException { Properties prop = new Properties(); InputStream istream = getClass().getClassLoader().getResourceAsStream("com/file/resources/searchtree.properties"); List<BinaryNode<String, String>> li = null; try { prop.load(istream); } catch (IOException e) { e.printStackTrace(); } String pathLocation=prop.getProperty("path"); File file = new File(pathLocation); if(!file.exists()){ try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } BufferedReader br = new BufferedReader(new FileReader(file)); if(br.readLine()!=null){ int size = deserialize(tree); br.close(); return(size); }else{ tree.add("Ram GC","DW-210"); tree.add("Hari Shrestha","DW-211"); tree.add("Shyam Karki","DW-2100"); li = tree.inOrder(tree.returnRoot()); System.out.println("size before: "+li.size()); for(int i=li.size()-1; i>=0; i--) { serialize(li.get(i).key,li.get(i).value); } br.close(); return(li.size()); } }
5
public void draw (Graphics g) { for(int i = 0; i < button.length; i++) { if(button[i].contains(Screen.mse)) { g.setColor(new Color(0,0,0)); g.fillRect( button[i].x, button[i].y, button[i].width, button[i].height ); } g.drawImage( Screen.tileset_res[0], button[i].x, button[i].y, button[i].width, button[i].height, null ); if(buttonID[i] != Value.airAir) { g.drawImage( Screen.tileset_air[buttonID[i]], button[i].x + itemIn, button[i].y + itemIn, button[i].width - (itemIn * 2), button[i].height - (itemIn * 2), null ); if(button[i].contains(Screen.mse)) { g.setColor(new Color(255, 255, 255, 100)); g.setFont(new Font("Times New Roman", Font.ITALIC, 20)); g.drawString( buttonDescription[i], Screen.mse.x, Screen.mse.y ); } } if(buttonPrice[i] > 0) { g.setColor(new Color(255,255,0)); g.setFont(new Font("Courier New", Font.BOLD, 14)); g.drawString( "$" + buttonPrice[i] + "", button[i].x + itemIn, button[i].y + (itemIn * 4) ); } } g.drawImage( Screen.tileset_res[1], buttonHealth.x, buttonHealth.y, buttonHealth.width, buttonHealth.height, null ); g.drawImage( Screen.tileset_res[2], buttonCoins.x, buttonCoins.y, buttonCoins.width, buttonCoins.height, null ); g.setFont(new Font("Courier New", Font.BOLD, 14)); g.setColor(new Color(250,250,250)); g.drawString( "" + Screen.health, buttonHealth.x + buttonHealth.width + iconSpace, buttonHealth.y + iconSpaceY ); g.drawString( "" + Screen.coinage, buttonCoins.x + buttonCoins.width + iconSpace, buttonCoins.y + iconSpaceY ); g.setColor(new Color(0,0,0)); g.drawString( "Goal " + Screen.killed + "/" + Screen.killsToWin, buttonGoal.x + buttonGoal.width + iconSpace, buttonGoal.y - iconSpaceY ); // g.drawString("Goal" + Screen.coinage, buttonCoins.x + 2*buttonCoins.width + iconSpace, buttonCoins.y + iconSpaceY); if(holdsItem) { g.drawImage( Screen.tileset_air[heldID], Screen.mse.x - ((button[0].width - (itemIn * 2)) / 2) + itemIn, Screen.mse.y - ((button[0].width - (itemIn * 2)) / 2) + itemIn, button[0].width - (itemIn * 2), button[0].height - (itemIn * 2), null ); } }
6
@Override public List<Integer> save(List<TourType> beans, GenericSaveQuery saveGeneric, Connection conn) throws DaoQueryException { try { return saveGeneric.sendQuery(SAVE_QUERY, conn, Params.fill(beans, (TourType bean) -> { Object[] objects = new Object[1]; objects[0] = bean.getNameTourType(); return objects; })); } catch (DaoException ex) { throw new DaoQueryException(ERR_TOURTYPE_SAVE, ex); } }
1
public void LoadSubGate(ObjectInputStream s) throws IOException, ClassNotFoundException { int numSignals = s.readInt(); mySignals = new Vector<Signal>(); for (int a = 0; a < numSignals; a++) { Signal newSignal = new Signal(); newSignal.Set(s.readBoolean()); newSignal.working = s.readBoolean(); mySignals.addElement(newSignal); } for (int a = 0; a < 8; a++) { int sigIndex = s.readInt(); if (sigIndex >= 0) { portSignals[a].internalSignal = mySignals.elementAt(sigIndex); } portSignals[a].type = s.readInt(); } int numGates = s.readInt(); for (int a = 0; a < numGates; a++) { Gate newGate = new Gate((String) s.readObject()); newGate.state = s.readBoolean(); myGates.addElement(newGate); for (int b = 0; b < 8; b++) { int sigIndex = s.readInt(); if (sigIndex >= 0) { newGate.portSignals[b].externalSignal = mySignals.elementAt(sigIndex); } } if (newGate.type.equalsIgnoreCase("Chip")) { newGate.LoadSubGate(s); } } speed = s.readInt(); }
7
public static boolean checkSumSign(BinaryFloatingPoint A, BinaryFloatingPoint B) { return (A.isSign() && B.isSign()) ? true : (!A.isSign() && !B.isSign()) ? false : (Math.abs(A.floatValue(false)) >= Math.abs(B.floatValue(false)) && !A.isSign()) || (Math.abs(A.floatValue(false)) <= Math.abs(B.floatValue(false)) && A.isSign()) ? false : true; }
8
public MainWindow(final NamiBeitrag namiBeitrag, final LetterDirectory letterDirectory, final NamiBeitragConfiguration conf) { letterGenerator = new LetterGenerator(namiBeitrag.getSessionFactory(), letterDirectory, conf); reportViewer = new ReportViewer(namiBeitrag.getSessionFactory()); setTitle("NamiBeitrag"); getContentPane().setLayout( new MigLayout("", "[grow][grow]", "[grow][grow][grow][][][]")); /**** NaMi ****/ JPanel panelNami = new JPanel(); getContentPane().add(panelNami, "cell 0 0,grow"); panelNami.setBorder(new TitledBorder("NaMi-Zugriff")); panelNami.setLayout(new MigLayout("", "[]", "[][][]")); JButton btnSync = new JButton("Mitglieder mit NaMi synchronisieren"); panelNami.add(btnSync, MIG_BUTTON_CONSTRAINTS); btnSync.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { namiBeitrag.syncMitglieder(); } catch (NamiApiException | IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } }); JButton btnFetch = new JButton("<html>Beitragszahlungen aus NaMi holen" + "<br>(von NaMi momentan nicht unterstützt)"); panelNami.add(btnFetch, MIG_BUTTON_CONSTRAINTS); btnFetch.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { namiBeitrag.fetchBeitragszahlungen(); } catch (NamiApiException | IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } }); JButton btnCsvImport = new JButton("Rechnung im CSV-Format einlesen"); panelNami.add(btnCsvImport, MIG_BUTTON_CONSTRAINTS); btnCsvImport.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { RechnungCsvImport imp = new RechnungCsvImport(namiBeitrag .getSessionFactory()); RechnungImportDialog diag = new RechnungImportDialog( MainWindow.this); diag.setVisible(true); if (diag.isAccepted()) { imp.importCsv(diag.getChosenFile(), diag.getRechnungsNummer(), diag.getRechnungsDatum()); } } }); /**** Vorausberechnungen ****/ JPanel panelVorausberechnungen = new JPanel(); getContentPane().add(panelVorausberechnungen, "cell 1 0,grow"); panelVorausberechnungen .setBorder(new TitledBorder("Vorausberechnungen")); panelVorausberechnungen.setLayout(new MigLayout("", "[]", "[][][]")); JButton btnVorausberechnung = new JButton( "Vorausberechnung für alle Mitglieder ..."); panelVorausberechnungen .add(btnVorausberechnung, MIG_BUTTON_CONSTRAINTS); btnVorausberechnung.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { HalbjahrMitgliedSelectDialog halbjahrSel; halbjahrSel = new HalbjahrMitgliedSelectDialog(MainWindow.this); halbjahrSel.setVisible(true); if (halbjahrSel.getChosenHalbjahr() != null) { namiBeitrag.vorausberechnung(halbjahrSel .getChosenHalbjahr()); } } }); JButton btnVorausberechnungUpdate = new JButton( "Vorausberechnung aktualisieren ..."); panelVorausberechnungen.add(btnVorausberechnungUpdate, MIG_BUTTON_CONSTRAINTS); btnVorausberechnungUpdate.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { HalbjahrMitgliedSelectDialog halbjahrMglSel; halbjahrMglSel = new HalbjahrMitgliedSelectDialog( MainWindow.this, namiBeitrag.getSessionFactory()); halbjahrMglSel.setVisible(true); if (halbjahrMglSel.getChosenHalbjahr() != null && halbjahrMglSel.getChosenMitgliedId() != -1) { namiBeitrag.aktualisiereVorausberechnung( halbjahrMglSel.getChosenHalbjahr(), halbjahrMglSel.getChosenMitgliedId()); } } }); JButton btnVorausberechnungDelete = new JButton( "Vorausberechnungen für Halbjahr löschen ..."); panelVorausberechnungen.add(btnVorausberechnungDelete, MIG_BUTTON_CONSTRAINTS); btnVorausberechnungDelete.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { HalbjahrMitgliedSelectDialog halbjahrSel; halbjahrSel = new HalbjahrMitgliedSelectDialog(MainWindow.this); halbjahrSel.setVisible(true); if (halbjahrSel.getChosenHalbjahr() != null) { namiBeitrag.loescheVorausberechnungen(halbjahrSel .getChosenHalbjahr()); } } }); /**** Buchungen ****/ JPanel panelBuchungen = new JPanel(); getContentPane().add(panelBuchungen, "cell 0 1,grow"); panelBuchungen.setBorder(new TitledBorder("")); panelBuchungen.setLayout(new MigLayout("", "[]", "[][][]")); JButton btnBeitragskonto = new JButton("Beitragskonto"); panelBuchungen.add(btnBeitragskonto, MIG_BUTTON_CONSTRAINTS); btnBeitragskonto.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { MitgliedAnzeigenWindow beitragskontoWin = new MitgliedAnzeigenWindow( namiBeitrag.getSessionFactory()); beitragskontoWin.setVisible(true); } }); JButton btnNeueBuchung = new JButton("Neue Buchung"); panelBuchungen.add(btnNeueBuchung, MIG_BUTTON_CONSTRAINTS); btnNeueBuchung.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { BuchungDialog diag = new BuchungDialog(namiBeitrag .getSessionFactory()); diag.setVisible(true); } }); /**** Mandate ****/ JPanel panelMandate = new JPanel(); getContentPane().add(panelMandate, "cell 1 1,grow"); panelMandate.setBorder(new TitledBorder("")); panelMandate.setLayout(new MigLayout("", "[]", "[][]")); JButton btnMandateErfassen = new JButton("Mandat erfassen"); panelMandate.add(btnMandateErfassen, MIG_BUTTON_CONSTRAINTS); btnMandateErfassen.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JFrame win = new MandatErstellenWindow(namiBeitrag .getSessionFactory()); win.setVisible(true); } }); JButton btnMandateVerwalten = new JButton("Mandate verwalten"); panelMandate.add(btnMandateVerwalten, MIG_BUTTON_CONSTRAINTS); btnMandateVerwalten.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JFrame win = new MandatVerwaltenWindow(namiBeitrag .getSessionFactory()); win.setVisible(true); } }); JButton btnMitgliederOhneSepa = new JButton( "Mitglieder ohne gültiges SEPA-Mandat anzeigen"); panelMandate.add(btnMitgliederOhneSepa, MIG_BUTTON_CONSTRAINTS); btnMitgliederOhneSepa.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { reportViewer.viewMitgliederOhneSepaMandat(); } }); /**** Rechnungen ****/ JPanel panelRechnungen = new JPanel(); getContentPane().add(panelRechnungen, "cell 0 2,grow"); panelRechnungen.setBorder(new TitledBorder("")); panelRechnungen.setLayout(new MigLayout("", "[]", "[][]")); JButton btnRechnungenErstellen = new JButton("Rechnungen erstellen"); panelRechnungen.add(btnRechnungenErstellen, MIG_BUTTON_CONSTRAINTS); btnRechnungenErstellen.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { RechnungenErstellenWindow win = new RechnungenErstellenWindow( namiBeitrag.getSessionFactory(), letterGenerator); win.setVisible(true); } }); JButton btnRechnungenVerwalten = new JButton("Rechnungen verwalten"); panelRechnungen.add(btnRechnungenVerwalten, MIG_BUTTON_CONSTRAINTS); btnRechnungenVerwalten.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JFrame win = new RechnungenVerwaltenWindow(namiBeitrag .getSessionFactory(), letterGenerator); win.setVisible(true); } }); /**** Lastschriften ****/ JPanel panelLastschriften = new JPanel(); getContentPane().add(panelLastschriften, "cell 1 2,grow"); panelLastschriften.setBorder(new TitledBorder("")); panelLastschriften.setLayout(new MigLayout("", "[]", "[][]")); JButton btnLastschriftenErstellen = new JButton( "Lastschriften erstellen"); panelLastschriften.add(btnLastschriftenErstellen, MIG_BUTTON_CONSTRAINTS); btnLastschriftenErstellen.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JFrame win = new LastschriftErstellenWindow(namiBeitrag .getSessionFactory()); win.setVisible(true); } }); JButton btnLastschriftenVerwalten = new JButton( "Lastschriften verwalten"); panelLastschriften.add(btnLastschriftenVerwalten, MIG_BUTTON_CONSTRAINTS); btnLastschriftenVerwalten.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JFrame win = new LastschriftVerwaltenWindow(namiBeitrag .getSessionFactory(), letterGenerator, conf); win.setVisible(true); } }); /**** Briefe verwalten ****/ JPanel panelBriefeVerwalten = new JPanel(); getContentPane().add(panelBriefeVerwalten, "cell 0 3,grow"); panelBriefeVerwalten.setBorder(new TitledBorder("")); panelBriefeVerwalten.setLayout(new MigLayout("", "[]", "[]")); JButton btnBriefeVerwalten = new JButton("Briefe verwalten"); panelBriefeVerwalten.add(btnBriefeVerwalten, MIG_BUTTON_CONSTRAINTS); btnBriefeVerwalten.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JFrame win = new BriefeWindow(namiBeitrag.getSessionFactory(), letterDirectory, conf); win.setVisible(true); } }); /**** Abmeldungen ****/ JPanel panelAbmeldungen = new JPanel(); getContentPane().add(panelAbmeldungen, "cell 1 3,grow"); panelAbmeldungen.setBorder(new TitledBorder("")); panelAbmeldungen.setLayout(new MigLayout("", "[]", "[][]")); JButton btnAbmeldungVormerken = new JButton("Abmeldung vormerken"); panelAbmeldungen.add(btnAbmeldungVormerken, MIG_BUTTON_CONSTRAINTS); btnAbmeldungVormerken.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JFrame win = new AbmeldungErstellenWindow(namiBeitrag .getSessionFactory()); win.setVisible(true); } }); JButton btnAbmeldungenVerwalten = new JButton("Abmeldungen verwalten"); panelAbmeldungen.add(btnAbmeldungenVerwalten, MIG_BUTTON_CONSTRAINTS); btnAbmeldungenVerwalten.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JFrame win = new AbmeldungenAnzeigenWindow(namiBeitrag .getSessionFactory()); win.setVisible(true); } }); /**** Auswertungen ****/ JPanel panelAuswertungen = new JPanel(); getContentPane().add(panelAuswertungen, "cell 0 4,grow"); panelAuswertungen.setBorder(new TitledBorder("Auswertungen")); panelAuswertungen.setLayout(new MigLayout("", "[]", "[][]")); JButton btnRepAbrechnungHalbjahr = new JButton("Abrechnung Halbjahr"); panelAuswertungen.add(btnRepAbrechnungHalbjahr, MIG_BUTTON_CONSTRAINTS); btnRepAbrechnungHalbjahr.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { HalbjahrMitgliedSelectDialog halbjahrSel; halbjahrSel = new HalbjahrMitgliedSelectDialog(MainWindow.this); halbjahrSel.setVisible(true); Halbjahr halbjahr = halbjahrSel.getChosenHalbjahr(); if (halbjahr != null) { reportViewer.viewAbrechnungHalbjahr(halbjahr); } } }); /**** Beenden ****/ JButton buttonClose = new JButton("Beenden"); getContentPane().add(buttonClose, "cell 0 5,span,alignx center"); buttonClose.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.exit(0); } }); pack(); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }
8
public static ActionType SelectActionComById(int id) throws SQLException { String query =""; ActionType Action = new ActionType(); ResultSet resultat; try { query = "SELECT * from ACTION_TYPE where ID_ACTION_TYPE=? "; PreparedStatement pStatement = ConnectionBDD.getInstance().getPreparedStatement(query); pStatement.setInt(1, id); resultat = pStatement.executeQuery(); while (resultat.next()) { Action = new ActionType(resultat.getInt("ID_ACTION_TYPE"),resultat.getString("TYP_LIB")); } } catch (SQLException ex) { Logger.getLogger(RequetesActionType.class.getName()).log(Level.SEVERE, null, ex); } return Action; }
2
public void upX(){ x += moveX; if (x+width>level.getLength()){ x = level.getLength()-width; } if (x<0) { // begin lock x = 0; } }
2
public void accessSpace(int space,int buttonType){ //LEFT CLICK: if(buttonType==1){ /*if(Screen.mouseCommand == 6){ //decide wich ones can be built: if(canBeBuilt(items.get(space).type)){ Screen.menuItemToBuild = space; System.out.println("Gana build a "+items.get(space).type); } }**/ } //RIGHT CLICK: if(buttonType==3){ System.out.println(space); if(!queue.type.equals(items.get(space).type)){ switchAnItemWithQueue(space); } else{ if(items.get(space).count<items.get(space).maxCount){ for(int i = queue.count;i>0;i--){ if(items.get(space).count>=items.get(space).maxCount){ break; } items.get(space).count++; queue.count--; } if(queue.count==0){ queue.type="nothing"; queue.maxCount=0; } } else if(items.get(space).count==items.get(space).maxCount){ switchAnItemWithQueue(space); } } } }
8
final public RGB Colour() throws ParseException { final Expression e1, e2, e3; switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case LBRACKET: jj_consume_token(LBRACKET); e1 = FloatExpression(); jj_consume_token(COMMA); e2 = FloatExpression(); jj_consume_token(COMMA); e3 = FloatExpression(); jj_consume_token(RBRACKET); {if (true) return new RGB(e1, e2, e3);} break; case STRING_END: case STRING: case IDENTIFIER: case CHARACTER: case VARIABLE: e1 = StringExpression(IN_STRING); {if (true) return new RGB(e1);} break; default: jj_la1[39] = jj_gen; jj_consume_token(-1); throw new ParseException(); } throw new Error("Missing return statement in function"); }
9
public void paint(Graphics g2) { if (this.applet != null) { return; } int w = getWidth() / 2; int h = getHeight() / 2; if ((this.img == null) || (this.img.getWidth() != w) || (this.img.getHeight() != h)) { this.img = createVolatileImage(w, h); } Graphics g = this.img.getGraphics(); for (int x = 0; x <= w / 32; x++) { for (int y = 0; y <= h / 32; y++) { g.drawImage(this.bgImage, x * 32, y * 32, null); } } g.setColor(Color.LIGHT_GRAY); String msg = "Updating Minecraft"; if (this.gameUpdater.fatalError) { msg = "Failed to launch"; } g.setFont(new Font(null, 1, 20)); FontMetrics fm = g.getFontMetrics(); g.drawString(msg, w / 2 - fm.stringWidth(msg) / 2, h / 2 - fm.getHeight() * 2); g.setFont(new Font(null, 0, 12)); fm = g.getFontMetrics(); msg = this.gameUpdater.getDescriptionForState(); if (this.gameUpdater.fatalError) { msg = this.gameUpdater.fatalErrorDescription; } g.drawString(msg, w / 2 - fm.stringWidth(msg) / 2, h / 2 + fm.getHeight() * 1); msg = this.gameUpdater.subtaskMessage; g.drawString(msg, w / 2 - fm.stringWidth(msg) / 2, h / 2 + fm.getHeight() * 2); if (!this.gameUpdater.fatalError) { g.setColor(Color.black); g.fillRect(64, h - 64, w - 128 + 1, 5); g.setColor(new Color(32768)); g.fillRect(64, h - 64, this.gameUpdater.percentage * (w - 128) / 100, 4); g.setColor(new Color(2138144)); g.fillRect(65, h - 64 + 1, this.gameUpdater.percentage * (w - 128) / 100 - 2, 1); } g.dispose(); g2.drawImage(this.img, 0, 0, w * 2, h * 2, null); }
9
public ArrayList<Integer> maxset(ArrayList<Integer> a) { ArrayList<Integer> result = new ArrayList<>(); int currstart = 0, currend = 0, maxstart = 0, maxend = 0; long currsum = 0, maxsum = Integer.MIN_VALUE, seg = 0, maxseg = 0; for (int i = 0; i < a.size(); i++) { int element = a.get(i); if (element < 0 && i < a.size() - 1) { currstart = currend = i + 1; seg = 0; currsum = 0; } else { seg++; currsum += element; if (currsum > maxsum) { currend = maxend = i; maxstart = currstart; maxsum = currsum; maxseg = seg; } else if (currsum == maxsum) { if (seg > maxseg) { currend = maxend = i; maxstart = currstart; maxsum = currsum; maxseg = seg; } } if (i == a.size() - 1) { if (maxsum < 0) return new ArrayList<>(); for (i = maxstart; i <= maxend; i++) result.add(a.get(i)); return result; } } } return result; }
9
@EventHandler public void onEntityDeath(EntityDeathEvent event){ ItemStack drop = new ItemStack(Material.GOLD_NUGGET, 1); Entity entity = event.getEntity(); int chance = DeityNether.config.getDropChance(); if(entity instanceof PigZombie && entity.getWorld().getEnvironment() == Environment.NETHER){ event.getDrops().clear(); event.getDrops().add(new ItemStack(Material.ROTTEN_FLESH)); int rn = (int)Math.random() * ((100 - chance) + 1) + chance; if(rn < chance){ event.getDrops().add(drop); } }else if(entity instanceof Player){ PlayerStats.setLeaveTime((Player)event.getEntity(), true); } }
4
public boolean hasPeerId() { return this.peerId != null; }
0
private void rotateLeft(Node<K, V> root) { Node<K, V> left = root.left; Node<K, V> pivot = root.right; Node<K, V> pivotLeft = pivot.left; Node<K, V> pivotRight = pivot.right; // move the pivot's left child to the root's right root.right = pivotLeft; if (pivotLeft != null) { pivotLeft.parent = root; } replaceInParent(root, pivot); // move the root to the pivot's left pivot.left = root; root.parent = pivot; // fix heights root.height = Math.max(left != null ? left.height : 0, pivotLeft != null ? pivotLeft.height : 0) + 1; pivot.height = Math.max(root.height, pivotRight != null ? pivotRight.height : 0) + 1; }
4
public void remove(BacklogBean oBacklogBean) throws Exception { try { oMysql.conexion(enumTipoConexion); oMysql.removeOne(oBacklogBean.getId(), "backlog"); oMysql.desconexion(); } catch (Exception e) { throw new Exception("BacklogDao.remove: Error: " + e.getMessage()); } finally { oMysql.desconexion(); } }
1
public synchronized int getAmount() { int retVal = amount; if (retVal != 0) { if (state == STATE_RELEASED) { amount = 0; } else if (behavior == DETECT_INITAL_PRESS_ONLY) { state = STATE_WAITING_FOR_RELEASE; amount = 0; } } return retVal; }
3
public static BufferedImage compress(BMPcontainer bmPcontainer) { int newWidth; int newHeight; double ar = bmPcontainer.getAspectRatio(); if (ar > 1) { newWidth = 256; newHeight = (int) (newWidth / ar); } else { newHeight = 256; newWidth = (int) (newHeight * ar); } BufferedImage result = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB); double widthStep = bmPcontainer.getWidth() / newWidth; double heightStep = bmPcontainer.getHeight() / newHeight; int sourceX = 0; int sourceY = 0; for (int y = 0; y < newHeight; y++) { for (int x = 0; x < newWidth; x++) { result.setRGB(x, y, bmPcontainer.get(sourceX, sourceY).getRGB()); sourceX += widthStep; } sourceY += heightStep; sourceX = 0; } return result; }
3
public static String post(String adress,List<String> keys,List<String> values) throws IOException { String result = ""; OutputStreamWriter writer = null; BufferedReader reader = null; try { String data=""; if(keys != null && values != null) for(int i=0;i<keys.size();i++) { if (i!=0) data += "&"; data +=URLEncoder.encode(keys.get(i), "UTF-8")+"="+URLEncoder.encode(values.get(i), "UTF-8"); } URL url = new URL(adress); URLConnection conn = url.openConnection(); conn.setDoOutput(true); writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(data); writer.flush(); reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String ligne; while ((ligne = reader.readLine()) != null) { result+=ligne; } } catch (IOException e) { throw e; } finally { try { writer.close(); } catch(Exception e) { ; } try { reader.close(); } catch(Exception e) { ; } } return result; }
8
public static void main(String[] args) { MyFlow myFlow = new MyFlow(); myFlow.go(); }
0
public void play() { board.drawBoard(); do { for (Player player : players) { player.move(); board.drawBoard(); if (board.isFull()) { printStream.println("Game is a draw"); break; } if (board.hasWinner()) { // printStream.println(String.format("")) break; } } } while(!board.isFull() && !board.hasWinner()); }
5
public void spawn(){ x=rand.nextInt(Level.SIZE); y=rand.nextInt(Level.SIZE); while(l.world[x][y]!=TileType.AIR && l.world[x][y]!=TileType.FIRE && l.world[x][y]!=TileType.TORCH){ x=rand.nextInt(Level.SIZE); y=rand.nextInt(Level.SIZE); } }
3
private void randomTeleport(String arena, Player p) { ArrayList<Location> spawns = ffaconfig.getSpawns(arena); Random num = new Random(); if (spawns != null && spawns.size() > 0) { p.closeInventory(); p.teleport(spawns.get(num.nextInt(spawns.size()-1))); } else { p.sendMessage(prefix + "Unable to find spawn points :("); } }
2
@SuppressWarnings({ "rawtypes", "unchecked" }) public CreateEvent() { final JFrame eventFrame = new JFrame("New Event"); eventFrame.setAlwaysOnTop(true); eventFrame.setBackground(Color.WHITE); eventFrame.setResizable(false); eventFrame.setVisible(true); eventFrame.setLocationRelativeTo(CalendarPanel.bullseye); eventFrame.setSize(400, 300); JPanel eventPanel = new JPanel(); eventPanel.setBackground(Color.WHITE); eventFrame.getContentPane().add(eventPanel); eventPanel.setSize(400, 300); eventPanel.setVisible(true); eventPanel.setLayout(null); lblName = new JLabel("Name"); lblName.setBounds(10, 11, 83, 24); eventPanel.add(lblName); lblDesc = new JLabel("Description"); lblDesc.setBounds(10, 46, 83, 24); eventPanel.add(lblDesc); lblLoc = new JLabel("Location"); lblLoc.setBounds(10, 81, 83, 24); eventPanel.add(lblLoc); tFname = new JTextField(); tFname.setBounds(119, 13, 255, 20); eventPanel.add(tFname); tFname.setColumns(10); tFdesc = new JTextField(); tFdesc.setBounds(119, 48, 255, 20); eventPanel.add(tFdesc); tFdesc.setColumns(10); tFLoc = new JTextField(); tFLoc.setBounds(119, 83, 255, 20); eventPanel.add(tFLoc); tFLoc.setColumns(10); JLabel lblDate = new JLabel("Date"); lblDate.setFont(new Font("Helvetica Neue", Font.PLAIN, 13)); lblDate.setBounds(10, 116, 87, 25); eventPanel.add(lblDate); comboStartYear = new JComboBox(); comboStartYear.setBounds(119, 116, 77, 27); comboStartYear.addItem("Year"); comboStartYear.addItem("2014"); comboStartYear.addItem("2015"); comboStartYear.addItem("2016"); eventPanel.add(comboStartYear); comboStartMonth = new JComboBox(); comboStartMonth.setBounds(210, 116, 77, 27); comboStartMonth.addItem("Month"); for (int i = 1; i < 13; i++) { comboStartMonth.addItem(i); } eventPanel.add(comboStartMonth); comboStartDay = new JComboBox(); comboStartDay.addItem("Day"); for (int i = 1; i < 32; i++) { comboStartDay.addItem(i); } comboStartDay.setBounds(297, 116, 77, 27); eventPanel.add(comboStartDay); JLabel lblStart = new JLabel("Start"); lblStart.setBounds(10, 160, 87, 16); eventPanel.add(lblStart); comboStartH = new JComboBox(); comboStartH.setBounds(119, 155, 113, 27); comboStartH.addItem("Hour"); for (int i = 8; i < 23; i++) { comboStartH.addItem(i); } eventPanel.add(comboStartH); comboStartM = new JComboBox(); comboStartM.setBounds(257, 155, 117, 27); comboStartM.addItem("Minute"); for (int i = 0; i < 60; i++) { comboStartM.addItem(i); } eventPanel.add(comboStartM); JLabel lblEnd = new JLabel("End"); lblEnd.setBounds(10, 193, 100, 16); eventPanel.add(lblEnd); comboEndH = new JComboBox(); comboEndH.setBounds(119, 188, 113, 27); comboEndH.addItem("Hour"); for (int i = 8; i < 23; i++) { comboEndH.addItem(i); } eventPanel.add(comboEndH); comboEndM = new JComboBox(); comboEndM.setBounds(257, 188, 117, 27); comboEndM.addItem("Minute"); for (int i = 0; i < 60; i++) { comboEndM.addItem(i); } eventPanel.add(comboEndM); btnCancel = new JButton("Cancel"); btnCancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { eventFrame.dispose(); } }); btnCancel.setBounds(119, 238, 89, 23); eventPanel.add(btnCancel); lblMsg = new JLabel(""); lblMsg.setHorizontalAlignment(SwingConstants.CENTER); lblMsg.setBounds(164, 218, 173, 20); eventPanel.add(lblMsg); btnCreate = new JButton("Create"); btnCreate.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String stringStartYear = "\"" + comboStartYear.getSelectedItem().toString() + "\""; String stringStartMonth = "\"" + comboStartMonth.getSelectedItem().toString() + "\""; String stringStartDay = "\"" + comboStartDay.getSelectedItem().toString() + "\""; String stringStartTimeH = "\"" + comboStartH.getSelectedItem().toString() + "\""; String stringStartTimeM = "\"" + comboStartM.getSelectedItem().toString() + "\""; ArrayList<String> start = new ArrayList<String>(); start.add(stringStartYear); start.add(stringStartMonth); start.add(stringStartDay); start.add(stringStartTimeH); start.add(stringStartTimeM); String stringEndYear = "\"" + comboStartYear.getSelectedItem().toString() + "\""; String stringEndMonth = "\"" + comboStartMonth.getSelectedItem().toString() + "\""; String stringEndDay = "\"" + comboStartDay.getSelectedItem().toString() + "\""; String stringEndTimeH = "\"" + comboEndH.getSelectedItem().toString() + "\""; String stringEndTimeM = "\"" + comboEndM.getSelectedItem().toString() + "\""; ArrayList<String> end = new ArrayList<String>(); end.add(stringEndYear); end.add(stringEndMonth); end.add(stringEndDay); end.add(stringEndTimeH); end.add(stringEndTimeM); String name = tFname.getText(); String desc = tFdesc.getText(); String loc = tFLoc.getText(); try { String answer = Switch.createEvent(loc, CalendarLogin.currentUser.getUsername(), start, end, desc, name); if (answer.equals("0")) { eventFrame.dispose(); } else if (answer.equals("1")) { lblMsg.setText("Could not add event, please check date."); } } catch (Exception e1) { e1.printStackTrace(); } } }); btnCreate.setBounds(285, 238, 89, 23); eventPanel.add(btnCreate); }
9
public Solution search(State state, int goalN) { SearchTreeNode init = createSearchTreeNode(state, null, 0, 0); queue.add(init); while (!queue.isEmpty()) { SearchTreeNode node = dequeue(); if (visualize) { System.out.println(node.toString()); } if (node.state.isGoal()) { return new Solution(node, problem.pathCost(node.state), numNodes); } // Expand node and add all its children to the queue. numNodes++; visitedStates.add(node.getState().toString()); Collection<SearchTreeNode> childrenNodes = createSearchTreeNodes( node, node.state.getChildrenStates(problem)); for (SearchTreeNode childNode : childrenNodes) { enqueue(childNode); } } return null; }
4
private boolean diagonalDecrementingBlock(int[][] grid, LinkedList<Square> squareStore, boolean pickOne) { //Block - Diagonal dec if ((grid[0][0] == 1 && grid[1][1] == 1) && grid[2][2] != 2) { BuildAndAddSquareTwoTwo(squareStore); pickOne = updateGridTwoTwo(grid); } else if ((grid[1][1] == 1 && grid[2][2] == 1) && grid[0][0] != 2) { BuildAndAddSquareZeroZero(squareStore); pickOne = updateGridZeroZero(grid); } else if ((grid[0][0] == 1 && grid[2][2] == 1) && grid[1][1] != 2) { BuildAndAddSquareOneOne(squareStore); pickOne = updateGridOneOne(grid); } return pickOne; }
9
static public void printCoauthorTable() { Iterator it = Person.iterator(); int coauthors[] = new int[501]; Person pers; int c; while (it.hasNext()) { pers = (Person) it.next(); c = pers.getNumberOfCoauthors(); if (c > 500) c = 500; coauthors[c]++; } System.out.println(); System.out.println("person: coauthors"); System.out.println("Number of coauthors: Number of persons"); int n = 0; for (int j=0; j <= 500; j++) { if (coauthors[j] == 0) continue; n++; System.out.print(j + ": " + coauthors[j]+ " "); if (n%5 == 0) System.out.println(); } System.out.println(); }
5
@Override public void acceptButtonActionPerformed() { //Comprobation that closuredTo is a double value is needed try{ String selectedNames[] = ds.getSelectedData(); DataFrame dataFrame = mainApplication.getActiveDataFrame(); boolean selection[] = dataFrame.getValidCompositionsWithZeros(selectedNames); double dlevel[][] = dataFrame.getDetectionLevel(selectedNames); double[][]data = dataFrame.getNumericalData(selectedNames); double[][]vdata = coda.Utils.reduceData(data, selection); double power = Double.parseDouble(powerWith.getText()); String[] new_names = new String[selectedNames.length]; for(int i=0;i<selectedNames.length;i++) new_names[i] = selectedNames[i] + "^" + Double.toString(power); // = CoDaPack.center(df.getNumericalDataZeroFree(sel_names)); double[][] dpow = CoDaStats.powerData(vdata,power); if(performClosure.isSelected()){ double vclosureTo = Double.parseDouble(closureTo.getText()); double[][]d = coda.Utils.recoverData(CoDaStats.closure(dpow, vclosureTo), selection); double []total = CoDaStats.rowSum(data); for(int i=0;i<new_names.length;i++){ Variable var = new Variable(new_names[i], d[i]); for(int j=0;j<data[i].length;j++){ if(dlevel[i][j] != 0 & data[i][j] == 0){ var.set(j, new Zero( Math.pow(dlevel[i][j]/total[j], power) )); } } dataFrame.addData(new_names[i], var); } }else{ double[][]d = coda.Utils.recoverData(dpow, selection); for(int i=0;i<new_names.length;i++){ Variable var = new Variable(new_names[i], d[i]); for(int j=0;j<data[i].length;j++){ if(dlevel[i][j] != 0 & data[i][j] == 0){ var.set(j, new Zero( Math.pow(dlevel[i][j], power) )); } } dataFrame.addData(new_names[i], var); } } mainApplication.updateDataFrame(dataFrame); setVisible(false); }catch(NumberFormatException ex){ JOptionPane.showMessageDialog(this, "Power value must be a double"); } }
9
private void cargarCampos(int numAsiento){ try { r_con.Connection(); ResultSet rs=r_con.Consultar("select * from borrador_asientos where ba_nro_asiento="+numAsiento); Asiento asiento=null; renglon=0; BigDecimal debeTotal=new BigDecimal(0); BigDecimal haberTotal=new BigDecimal(0); while(rs.next()){ renglon++; asiento=new Asiento(rs.getInt(1),rs.getInt(2),rs.getDate(3).toString(), rs.getDate(6).toString(),rs.getDate(7).toString(), rs.getString(4),rs.getInt(5),rs.getString(8), rs.getString(9),rs.getFloat(10),rs.getFloat(11), rs.getBoolean(12),rs.getBoolean(13)); modelo.addRow(asiento.getRenglonModelo()); jTable1.setModel(modelo); BigDecimal asDebe=convertirEnBigDecimal(asiento.getDebe()+""); debeTotal=sumarBigDecimal(debeTotal+"",asDebe+""); BigDecimal asHaber=convertirEnBigDecimal(asiento.getHaber()+""); haberTotal=sumarBigDecimal(haberTotal+"",asHaber+""); } jTextField9.setText(debeTotal+""); jTextField11.setText(haberTotal+""); BigDecimal saldo=sumarBigDecimal(debeTotal+"","-"+haberTotal); jTextField10.setText(saldo+""); if(asiento!=null){ campoFecha.setText(fecha.convertirBarras(asiento.getFecha_contable())); jTextField2.setText(++renglon+""); if(asiento.getTipo().equals("Asiento Apertura")){ jRadioButton1.setSelected(true); } else{ if(asiento.getTipo().equals("Asiento Normal")){ jRadioButton2.setSelected(true); } else{ jRadioButton3.setSelected(true); } } } r_con.cierraConexion(); } catch (SQLException ex) { r_con.cierraConexion(); Logger.getLogger(GUI_Cargar_Asiento.class.getName()).log(Level.SEVERE, null, ex); } }
5
private void showHelp(CommandSender sender) { sender.sendMessage("Commands:"); sender.sendMessage(" /soundcheck - Plugin administration command"); if (Perms.canUsePlaySound(sender)) { sender.sendMessage(" /playsound - Play an individual sounds"); } if (Perms.canUsePlayFx(sender)) { sender.sendMessage(" /playfx - Play an individual effects"); } if (Perms.canUsePlayEfx(sender)) { sender.sendMessage(" /playefx - Play an individual entity-effects"); } if (Perms.canUseSequence(sender)) { sender.sendMessage(" /sequence - Play configured sound/effect sequences"); } }
4
public Frame() { setBackground(Color.GRAY); try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException e1) { } catch (InstantiationException e1) { } catch (IllegalAccessException e1) { } catch (UnsupportedLookAndFeelException e1) { } setIconImage(Toolkit.getDefaultToolkit().getImage(Frame.class.getResource("/tiles/X_wa.png"))); setTitle("Editor"); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(0, 0, (int)(getToolkit().getScreenSize ().width*.66), (int)(getToolkit().getScreenSize ().height-400*.66)); setExtendedState(java.awt.Frame.MAXIMIZED_BOTH); JMenuBar menuBar = new JMenuBar(); menuBar.setMargin(new Insets(0, 0, 4, 0)); setJMenuBar(menuBar); JButton btnOpen = new JButton("open"); JButton btnSave = new JButton("save"); contentPane = new JPanel(); contentPane.setBackground(Color.GRAY); contentPane.setBorder(new LineBorder(new Color(0, 0, 0))); setContentPane(contentPane); contentPane.setLayout(new BorderLayout(0, 0)); JPanel panel = new JPanel(); panel.setBackground(Color.GRAY); panel.setBorder(null); contentPane.add(panel,BorderLayout.CENTER); panel.setLayout(new BorderLayout(0, 0)); final JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP); panel.add(tabbedPane); JButton btnNewButton_1 = new JButton("New"); btnNewButton_1.setBounds(10, 11, 60, 23); btnNewButton_1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Map m = New.n(getLocationOnScreen(),getSize()); if(m!=null) { Cursor.setItem("grass"); maps.add(new ScrollPane(m)); tabbedPane.addTab("map_"+(maps.size()),maps.get(maps.size()-1)); } } }); menuBar.add(btnNewButton_1); menuBar.add(btnOpen); menuBar.add(btnSave); JPanel panel_1 = new JPanel(); panel_1.setBorder(new BevelBorder(BevelBorder.RAISED, null, null, null, null)); contentPane.add(panel_1,BorderLayout.EAST); panel_1.setPreferredSize(new Dimension(200,620)); panel_1.setLayout(new BorderLayout(0, 0)); JScrollPane scrollPane = new JScrollPane(); panel_1.add(scrollPane); final Itembrowser tree = new Itembrowser(); scrollPane.setViewportView(tree); tree.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null)); JPanel panel_3 = new JPanel(); panel_3.setPreferredSize(new Dimension(200,230)); panel_1.add(panel_3, BorderLayout.NORTH); panel_3.setLayout(null); minimap = new Minimap(); minimap.setBounds(10, 11, 180, 135); panel_3.add(minimap); minimap.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null)); minimap.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5)); JPanel panel_2 = new JPanel(); panel_2.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null)); panel_2.setBounds(10, 168, 180, 49); panel_3.add(panel_2); panel_2.setLayout(null); JButton btnNewButton = new JButton(""); btnNewButton.setBounds(10, 11, 25, 23); panel_2.add(btnNewButton); btnNewButton.setIcon(new ImageIcon(Frame.class.getResource("/icons/maus.png"))); JButton button = new JButton(""); button.setBounds(45, 11, 25, 23); panel_2.add(button); JButton button_1 = new JButton(""); button_1.setBounds(97, 11, 25, 23); panel_2.add(button_1); button_1.setIcon(new ImageIcon(Frame.class.getResource("/icons/pinsel.png"))); JButton button_3 = new JButton(""); button_3.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) {Cursor.addToSize(1);} }); button_3.setBounds(132, 11, 15, 15); panel_2.add(button_3); button_3.setIcon(new ImageIcon(Frame.class.getResource("/icons/plus.jpg"))); JButton button_2 = new JButton(""); button_2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) {Cursor.addToSize(-1);} }); button_2.setBounds(132, 29, 15, 15); panel_2.add(button_2); button_2.setIcon(new ImageIcon(Frame.class.getResource("/icons/minus.jpg"))); Component horizontalStrut = Box.createHorizontalStrut(10); panel_1.add(horizontalStrut, BorderLayout.WEST); Component verticalStrut = Box.createVerticalStrut(7); panel_1.add(verticalStrut, BorderLayout.SOUTH); Component horizontalStrut_2 = Box.createHorizontalStrut(4); panel_1.add(horizontalStrut_2, BorderLayout.EAST); }
5
public String getEmail() { return email; }
0
public void resolveBackupDirectory() { // Load the backup_location file to get the backup folder path. If it doesn't exist, it's // the first run File backup_file = new File("backup_location"); if(backup_file.exists()) { Scanner in = null; try { // Read the path in, and if it's valid, set the backup location to this path. If // it's not valid, it's the first run in = new Scanner(new FileReader(backup_file)); File backupLocation = Paths.get(in.nextLine()).toFile(); if(backupLocation.exists()) { Main.backupDirectory = backupLocation.toPath(); logger.info("Located backup location: " + Main.backupDirectory); } } catch(IOException e) { // If an exception occurs, we couldn't retrieve the backup directory, so must set it // to null logger.error("Could not read in backup_location file", e); } catch(InvalidPathException e) { logger.error("Backup directory path is invalid", e); Main.backupDirectory = null; } catch(SecurityException e) { logger.error("Security error: cannot access backup directory", e); Main.backupDirectory = null; } finally { if(in != null) { in.close(); } } // If the database file isn't in the backup folder, it's not a valid folder if(Main.backupDirectory == null || !Main.backupDirectory.resolve(".revisions.db").toFile().exists()) { logger.error("The backup directory linked in \"backup_location\" is invalid: " + Main.backupDirectory); Main.backupDirectory = null; JOptionPane.showMessageDialog(null, "A backup location record exists, but is invalid. The first-run wizard " + "will be displayed.", "Error", JOptionPane.WARNING_MESSAGE); } } }
8
public int getBrakes() { return brakes; }
0
public double[] standardizedItemRanges(){ if(!this.dataPreprocessed)this.preprocessData(); if(!this.variancesCalculated)this.meansAndVariances(); return this.standardizedItemRanges; }
2
public void mousePressed(MouseEvent me) { // Track the current tree node selected // so there by the query token. JTree tree = (JTree) me.getSource(); if (SwingUtilities.isRightMouseButton(me)) { int row = tree.getRowForLocation(me.getX(), me.getY()); if (row != -1) tree.setSelectionRow(row); } node = null; selectedToken = null; TreePath path = tree.getSelectionPath(); if (path != null) { node = (DefaultMutableTreeNode) path.getLastPathComponent(); if (node.getUserObject() instanceof QueryTokens._Base || node instanceof BrowserItems.TableTreeItem) { selectedToken = (QueryTokens._Base) node.getUserObject(); } else if (node instanceof BrowserItems.ConditionQueryTreeItem) { selectedToken = ((BrowserItems.ConditionQueryTreeItem) node).getCondition(); } else if (node instanceof BrowserItems.AbstractQueryTreeItem) { QueryExpression qe = ((BrowserItems.AbstractQueryTreeItem) node).getQueryExpression(); if (qe instanceof SubQuery) selectedToken = (SubQuery) qe; } } }
8
public static void main(String[] args) { Random rand = new Random(47); int i = rand.nextInt(); int j = rand.nextInt(); printBinaryInt("-1", -1); printBinaryInt("+1", +1); int maxpos = 2147483647; printBinaryInt("maxpos", maxpos); int maxneg = -2147483648; printBinaryInt("maxneg", maxneg); printBinaryInt("i", i); printBinaryInt("~i", ~i); printBinaryInt("-i", -i); printBinaryInt("j", j); printBinaryInt("i & j", i & j); printBinaryInt("i | j", i | j); printBinaryInt("i ^ j", i ^ j); printBinaryInt("i << 5", i << 5); printBinaryInt("i >> 5", i >> 5); printBinaryInt("(~i) >> 5", (~i) >> 5); printBinaryInt("i >>> 5", i >>> 5); printBinaryInt("(~i) >>> 5", (~i) >>> 5); long l = rand.nextLong(); long m = rand.nextLong(); printBinaryLong("-1L", -1L); printBinaryLong("+1L", +1L); long ll = 9223372036854775807L; printBinaryLong("maxpos", ll); long lln = -9223372036854775808L; printBinaryLong("maxneg", lln); printBinaryLong("l", l); printBinaryLong("~l", ~l); printBinaryLong("-l", -l); printBinaryLong("m", m); printBinaryLong("l & m", l & m); printBinaryLong("l | m", l | m); printBinaryLong("l ^ m", l ^ m); printBinaryLong("l << 5", l << 5); printBinaryLong("l >> 5", l >> 5); printBinaryLong("(~l) >> 5", (~l) >> 5); printBinaryLong("l >>> 5", l >>> 5); printBinaryLong("(~l) >>> 5", (~l) >>> 5); }
0
public static void open(String url){ String os = System.getProperty("os.name").toLowerCase(); Runtime rt = Runtime.getRuntime(); try{ if (os.indexOf( "win" ) >= 0) { // this doesn't support showing urls in the form of "page.html#nameLink" rt.exec( "rundll32 url.dll,FileProtocolHandler " + url); } else if (os.indexOf( "mac" ) >= 0) { rt.exec( "open " + url); } else if (os.indexOf( "nix") >=0 || os.indexOf( "nux") >=0) { // Do a best guess on unix until we get a platform independent way // Build a list of browsers to try, in this order. String[] browsers = {"epiphany", "firefox", "mozilla", "konqueror", "netscape","opera","links","lynx"}; // Build a command string which looks like "browser1 "url" || browser2 "url" ||..." StringBuffer cmd = new StringBuffer(); for (int i=0; i<browsers.length; i++) cmd.append( (i==0 ? "" : " || " ) + browsers[i] +" \"" + url + "\" "); rt.exec(new String[] { "sh", "-c", cmd.toString() }); } }catch (Exception e){ e.printStackTrace(); System.out.println("Failed to open url"); } }
7
@Override public float calculateDesire() { float desire = 0; //figure out the distance between player and mob int actorX = ai.getActor().getMapX(); int playerX = registry.getClosestPlayerX(ai.getActor().getCenterPoint(), registry.getScreenWidth()); int distance = Math.abs(playerX - actorX); //see if the mob needs to be scared //closer the player is, the more scared the mob is if (distance >= SAFE_DISTANCE) { desire = 0; } else { desire = 1.0f - ((float) distance / (float) SAFE_DISTANCE); } desire *= bias; desire = validateDesire(desire); return desire; }
1
public void run() { boolean hasUpdate = true; while (hasUpdate) { hasUpdate = false; Set<String> keys = new HashSet<String>(this.r.keySet()); for (String rkey : keys) { double ru = this.r.get(rkey); try { BufferedReader reader = new BufferedReader( new InputStreamReader(new FileInputStream( this.graphPathStr))); String line = null; boolean notfound = true; while ((line = reader.readLine()) != null) { String[] fields = line.split("\t"); String ukey = fields[0]; if (ukey.compareTo(rkey) == 0) { int len = fields.length; int outdegree = len - 1; if (outdegree == 0 || ru / (double) outdegree <= EPSILON) continue; this.push(fields); hasUpdate = true; notfound = false; break; } } if (notfound) { this.push(new String[] { rkey }); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } }
9
public Var intern(Symbol sym){ if(sym.ns != null) { throw new IllegalArgumentException("Can't intern namespace-qualified symbol"); } IPersistentMap map = getMappings(); Object o; Var v = null; while((o = map.valAt(sym)) == null) { if(v == null) v = new Var(this, sym); IPersistentMap newMap = map.assoc(sym, v); mappings.compareAndSet(map, newMap); map = getMappings(); } if(o instanceof Var && ((Var) o).ns == this) return (Var) o; if(v == null) v = new Var(this, sym); warnOrFailOnReplace(sym, o, v); while(!mappings.compareAndSet(map, map.assoc(sym, v))) map = getMappings(); return v; }
7
public void mouseDragged(Point p) { //System.out.println("mousedragged"); //insert location mode if(mode==INSERTLOC){ if(curr!=-1){ mygraph.locations[curr].setPoint(p); changeNotify(); } } //insert path mode if(mode==INSERTPATH){ lineEndIndex=mygraph.findIndex(p); if((lineStartIndex!=-1)&&(lineEndIndex!=-1)&&lineStartIndex!=lineEndIndex){ mygraph.setEdge(lineStartIndex,lineEndIndex); changeNotify(); lineStartIndex=-1; lineEndIndex=-1; } } }
6