text
stringlengths
14
410k
label
int32
0
9
public Object execute(Node node) { Keyword key = (Keyword) node.getLeftChild().getTokenValue(); Node result = (Node) super.execute(node.getRightChild()); char[] ops = key.toString().substring(1, key.toString().length() - 1).toLowerCase().toCharArray(); for (int i = ops.length - 1; i >= 0; i--) { if (ops[i] == 'a') result = result.getLeftChild(); else { result = result.getRightChild(); if (result == null && i == 0) return new Node(new SpecialToken("(")); } } if (result instanceof Node) { switch (result.getToken().getType()) { case Boolean: case Character: case Number: case String: return result.getTokenValue(); } } return result.clone(); }
9
protected static Ptg calcRound( Ptg[] operands ) throws CalculationException { if( operands.length < 1 ) { return PtgCalculator.getNAError(); } double[] dd = PtgCalculator.getDoubleValueArray( operands ); if( dd == null ) { return new PtgErr( PtgErr.ERROR_NA );//20090130 KSC: propagate error } //if (dd.length != 2) return PtgCalculator.getError(); // we need to handle arrays sent in, just use the first and last elements. double num = dd[0]; double round = dd[dd.length - 1]; double res = 0; if( round == 0 ) {//return an int res = Math.round( num ); } else if( round > 0 ) { //round the decimal that number of spaces double tempnum = num * Math.pow( 10, round ); tempnum = Math.round( tempnum ); res = tempnum / Math.pow( 10, round ); } else { //round up the decimal that numbe of places round = round * -1; double tempnum = num / Math.pow( 10, round ); tempnum = Math.round( tempnum ); res = tempnum * Math.pow( 10, round ); } PtgNumber ptnum = new PtgNumber( res ); return ptnum; }
4
public static Hand OnePair(Rank pairRank, Rank firstKicker, Rank secondKicker, Rank thirdKicker) { return new Hand(HandRank.OnePair, null, pairRank, firstKicker, secondKicker, thirdKicker, Rank.Null); }
0
private void connectButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_connectButtonActionPerformed {//GEN-HEADEREND:event_connectButtonActionPerformed try { echoClient.connect(hostTextField.getText(), Integer.parseInt(portTextField.getText())); messageArrived("Connected"); } catch (IOException ex) { messageArrived(ex.toString()); } }//GEN-LAST:event_connectButtonActionPerformed
1
@Override public Task getTask(String jid, String tid) throws RemoteException { Task[] taskArray = null; synchronized (this.syncTaskList) { taskArray = this.syncTaskList.toArray(new Task[0]); } if (taskArray == null) { return null; } for (int i = this.syncTaskList.size() - 1; i >= 0; i--) { Task taskOnTaskTracker = this.syncTaskList.get(i); if (taskOnTaskTracker.getJobId().equals(jid) && taskOnTaskTracker.getTaskId().equals(tid)) { return taskOnTaskTracker; } } return null; }
4
public SchemaGraphComponent(mxGraph graph) { super(graph); mxGraphView graphView = new mxGraphView(graph) { /** * */ public void updateFloatingTerminalPoint(mxCellState edge, mxCellState start, mxCellState end, boolean isSource) { int col = getColumn(edge, isSource); if (col >= 0) { double y = getColumnLocation(edge, start, col); boolean left = start.getX() > end.getX(); if (isSource) { double diff = Math.abs(start.getCenterX() - end.getCenterX()) - start.getWidth() / 2 - end.getWidth() / 2; if (diff < 40) { left = !left; } } double x = (left) ? start.getX() : start.getX() + start.getWidth(); double x2 = (left) ? start.getX() - 20 : start.getX() + start.getWidth() + 20; int index2 = (isSource) ? 1 : edge.getAbsolutePointCount() - 1; edge.getAbsolutePoints().add(index2, new mxPoint(x2, y)); int index = (isSource) ? 0 : edge.getAbsolutePointCount() - 1; edge.setAbsolutePoint(index, new mxPoint(x, y)); } else { super.updateFloatingTerminalPoint(edge, start, end, isSource); } } }; graph.setView(graphView); }
7
public String getColumnName(int column) { int count = getColumnCount(); if (column == count - 1) return "Result"; int offset = 0; if(isMultiple){ offset = 1; if(column == 0) return "File"; } String word = ""; if(column <= (getInputCount()-1+offset) && column >= (offset)){ word = "Input"; } else if(column > (getInputCount()-1+offset)){ word = "Output"; column -= getInputCount(); } if (getInputCount()==1) return word; return word + " " + (column+1-offset); }
7
public void muteMedia() { if (Debug.audio) System.out.println("AudioPlayer -> muteMedia called"); if ((null != player) && realizeComplete) { gainControl.setMute(true); if (Debug.audio) System.out.println("AudioPlayer -> muteMedia set"); } }
4
public int getLength(){ return arraysBase.size(); }
0
public static boolean isChargedCreeper (Entity entity) { if (entity instanceof Creeper) { Creeper chargedcreeper = (Creeper) entity; if (chargedcreeper.isPowered()) { return true; } } return false; }
2
public static Population evolvePopulation(Population pop, int mutationPerEvo) { int cloneCounter = 0; Population newPopulation = new Population(pop.populationSize(), false); tournamentSize = (int) (pop.populationSize()*0.2); // Keep our best individual if elitism is enabled int elitismOffset = 0; if (elitism) { newPopulation.saveTour(0, pop.getFittest()); newPopulation.saveTour(1, tournamentSelection(pop)); elitismOffset = 2; } // Crossover population // Loop over the new population's size and create individuals from // Current population int k = 0; for (int i = elitismOffset; i < GlobalData.popSize +k; i++) { // Select parents Tour parent1 = tournamentSelection(pop); Tour parent2 = tournamentSelection(pop); // Crossover parents Tour child = crossover(parent1, parent2); if (mutationPerEvo == 0) mutate(child); reorder2Opt(child); // Add child to new population boolean flag = false; for(int j=0; j < newPopulation.populationSize() && !flag; j++) { if (newPopulation.getTour(j) != null && newPopulation.getTour(j).equals(child)) flag = true; } if (!flag) { newPopulation.saveTour(i, child); cloneCounter = 0; } else { cloneCounter++; if (cloneCounter < 15) k++; } } return newPopulation; }
9
@Override public void undo() { // Remove the Node node.getTree().removeNode(node); parent.removeChild(node, index); }
0
public void actionPerformed(ActionEvent e) { if (e.getSource() == btnExcluir) { try { do_btnExcluir_actionPerformed(e); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } if (e.getSource() == btnCancelar) { do_btnCancelar_actionPerformed(e); } }
3
private static Result doSendViaGcm(String message, Sender sender, DeviceInfo deviceInfo) throws IOException { // Trim message if needed. if (message.length() > 1000) { message = message.substring(0, 1000) + "[...]"; } // This message object is a Google Cloud Messaging object, it is NOT // related to the MessageData class Message msg = new Message.Builder().addData("message", message).build(); Result result = sender.send(msg, deviceInfo.getDeviceRegistrationID(), 5); if (result.getMessageId() != null) { String canonicalRegId = result.getCanonicalRegistrationId(); if (canonicalRegId != null) { endpoint.removeDeviceInfo(deviceInfo.getDeviceRegistrationID()); deviceInfo.setDeviceRegistrationID(canonicalRegId); endpoint.insertDeviceInfo(deviceInfo); } } else { String error = result.getErrorCodeName(); if (error.equals(Constants.ERROR_NOT_REGISTERED)) { endpoint.removeDeviceInfo(deviceInfo.getDeviceRegistrationID()); } } return result; }
4
public void removeService(Object service) throws Exception { int index = this._list.indexOf(service); if (index >= 0) { this._list.remove(index); if (service instanceof IService) { ((IService) service).uninitializeService(); } } }
2
private boolean analyzeLine(SourceLine sourceLine, List<SourceLine> lines) { for (String expression : properties.expressions) { Matcher m = Pattern.compile(expression).matcher(sourceLine.getContent()); if (m.matches()) { sourceLine.matchesAt(m.start(), m.end()); } } boolean shouldAdd = false; if (sourceLine.hasMatches() || workingCommand != null) { if (workingCommand == null && !isComment(sourceLine)) { workingCommand = identifyCommand(sourceLine, lines); } shouldAdd = true; } if (workingCommand != null && commandWasClosedAt(sourceLine)) { workingCommand = null; } return shouldAdd; }
8
public void positionVessel(EnumBoard player, EnumLine line, EnumColumn column, boolean vertical, EnumElement vessel) throws InvalidPositionException, GameInitializedException { if (this.init) { throw new GameInitializedException(); } else { Map<String, EnumElement> board = (player.equals(EnumBoard.PLAYER1)) ? this.boardPlayer1 : this.boardPlayer2; if (this.isEmpty(board, line, column)) { if (this.fitsVessel(line, column, vertical, vessel)) { this.addVessel(board, line, column, vertical, vessel); } else { throw new InvalidPositionException(); } } else { throw new InvalidPositionException(); } } }
4
public void configure(Configuration conf) throws ConfigurationException { conf.addConfigurable(this); ruleFile = conf.getProperty("broadcastTCPOutputConnector.rule"); if(ruleFile == null) throw new ConfigurationException("broadcastTCPOutputConnector.rule not specified"); String portString = conf.getProperty("broadcastTCPOutputConnector.port"); if(portString == null) throw new ConfigurationException("broadcastTCPOutputConnector.port not specified"); try { port = Integer.parseInt(portString); } catch(Exception e) { throw new ConfigurationException("broadcastTCPOutputConnector.port is not a number"); } String maxString = conf.getProperty("broadcastTCPOutputConnector.max"); if(maxString == null) throw new ConfigurationException("broadcastTCPOutputConnector.max not specified"); try { max = Integer.parseInt(maxString); } catch(Exception e) { throw new ConfigurationException("broadcastTCPOutputConnector.max is not a number"); } try { idleTimeout = Integer.parseInt(conf.getProperty("broadcastTCPOutputConnector.timeout")); } catch(Exception e) { idleTimeout = 10; } username = conf.getProperty("broadcastTCPOutputConnector.username"); password = conf.getProperty("broadcastTCPOutputConnector.password"); }
6
protected void scriptConvert(int pass, String relpath, File file) { if (pass == 1 && file.getName().endsWith("fcf")) { if (!relpath.contains("/")) { //If any subfolders exist, it's because the files were extracted on top of //an aborted earlier extraction. routeParser.parse(file, appendMap); } } else if (pass == 2 && file.getName().endsWith("ks")) { try { if (!routeParser.isIncludedInThisRun(file.getName())) { return; } processKSFile(file); } catch (Exception e) { e.printStackTrace(); } } }
7
public boolean ModificarTrata(Trata p){ if (p!=null) { cx.Modificar(p); return true; }else { return false; } }
1
void createChildren(Widget widget, boolean materialize) { if (contentProviderIsLazy) { Object element = widget.getData(); if (element == null && widget instanceof TreeItem) { // parent has not been materialized virtualMaterializeItem((TreeItem) widget); // try getting the element now that updateElement was called element = widget.getData(); } if (element == null) { // give up because the parent is still not materialized return; } Item[] children = getChildren(widget); if (children.length == 1 && children[0].getData() == null) { // found a dummy node virtualLazyUpdateChildCount(widget, children.length); children = getChildren(widget); } // touch all children to make sure they are materialized for (int i = 0; i < children.length; i++) { if (children[i].getData() == null) { if (materialize) { virtualLazyUpdateWidget(widget, i); } else { ((TreeItem)children[i]).clearAll(true); } } } return; } super.createChildren(widget, materialize); }
9
private String getCellToolTip(MouseEvent event) { String toolTip = null; int col = columnAtPoint(event.getPoint()); int row = rowAtPoint(event.getPoint()); if (row >= 0 && col >= 0) { TableCellRenderer renderer = getCellRenderer(row, col); Component component = prepareRenderer(renderer, row, col); if (component instanceof JLabel) { // Convert the event to the renderer's coordinate system Rectangle cellRect = getCellRect(row, col, false); if(cellRect.width < component.getPreferredSize().width) { toolTip = ((JLabel)component).getText(); } } } return toolTip; }
4
public void execute(MinersWife wife){ switch(rand.nextInt(3)) { case 0: System.out.println(wife.getName() + " Moppin' the floor"); break; case 1: System.out.println(wife.getName() + " Washin' the dishes"); break; case 2: System.out.println(wife.getName() + " Makin' the bed"); break; } }
3
public void setGame(Game game){ boolean test = false; if (test || m_test) { System.out.println("EndDisplay :: setGame() BEGIN"); } m_game = game; if (test || m_test) { System.out.println("EndDisplay :: setGame() END"); } }
4
public static void clearAllNodes() { eventQueue.pruneAllNodeEvents(); packetsInTheAir = new PacketsInTheAirBuffer(); for(Node n : nodes) { n.outgoingConnections.removeAndFreeAllEdges(); } nodes = createNewNodeCollection(); Node.resetIDCounter(); // new nodes restart their ID with 1 if(Global.isGuiMode){ GUI gui = Tools.getGUI(); gui.allNodesAreRemoved(); gui.redrawGUINow(); } }
2
public Shape getShape() { return shape; }
0
@SuppressWarnings("unchecked") public static SignalWriter createSignalWriter(SignalEntry signalEntry){ Properties unisensProperties = UnisensProperties.getInstance().getProperties(); String readerClassName = unisensProperties.getProperty(Constants.SIGNAL_WRITER.replaceAll("format", signalEntry.getFileFormat().getFileFormatName().toLowerCase())); if(readerClassName != null){ try{ Class<SignalWriter> readerClass = (Class<SignalWriter>)Class.forName(readerClassName); Constructor<SignalWriter> readerConstructor = readerClass.getConstructor(SignalEntry.class); return (SignalWriter)readerConstructor.newInstance(signalEntry); } catch (ClassNotFoundException e) { System.out.println("Class (" + readerClassName + ") could not be found!"); e.printStackTrace(); } catch (InstantiationException e) { System.out.println("Class (" + readerClassName + ") could not be instantiated!"); e.printStackTrace(); } catch (IllegalAccessException e) { System.out.println("Class (" + readerClassName + ") could not be accessed!"); e.printStackTrace(); } catch (ClassCastException ec) { ec.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } return null; }
9
private void New() { try { for(int i = 0; i < list.getProjectList().size(); i++) { StringTokenizer st = new StringTokenizer(list.getProjectList().get(i), " : "); String str = st.nextToken(); if(str.equals(NameTextField.getText())) { JOptionPane.showMessageDialog(buttonNew, "Project with such name is already exists"); return; } } } catch (RemoteException e1) { JOptionPane.showMessageDialog(buttonNew, "Disconect from server"); this.dispose(); LoginFrame log = new LoginFrame(); log.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); log.setVisible(true); } if(NameTextField.getText().length() == 0) { JOptionPane.showMessageDialog(buttonNew, "Enter projact name"); return; } setProjectName(NameTextField.getText()); PassFrame PF = new PassFrame(opf); PF.setDefaultCloseOperation(EXIT_ON_CLOSE); PF.setVisible(true); }
4
private final boolean isInvalidURICharacter( char c ) { for ( int i = 0; i < VALID_URI_CHARS.length; ++i ) { if ( VALID_URI_CHARS[i] == c ) { return false; } } return true; }
2
public String[] getOptions() { Vector result; String[] options; int i; result = new Vector(); if (getDebug()) result.add("-D"); if (getSilent()) result.add("-S"); result.add("-N"); result.add("" + getNumInstances()); if (getEstimator() != null) { result.add("-W"); result.add(getEstimator().getClass().getName()); } if ((m_Estimator != null) && (m_Estimator instanceof OptionHandler)) options = ((OptionHandler) m_Estimator).getOptions(); else options = new String[0]; if (options.length > 0) { result.add("--"); for (i = 0; i < options.length; i++) result.add(options[i]); } return (String[]) result.toArray(new String[result.size()]); }
7
public static ProtocolSignUp getProtocolSignup(String inString) throws JDOMException, IOException, TagFormatException { SAXBuilder mSAXBuilder = new SAXBuilder(); Document mDocument = mSAXBuilder.build(new StringReader(inString)); Element rootNode = mDocument.getRootElement(); String protType = rootNode.getName(); if (protType.equals(Tags.SESSION)) { String username = rootNode.getChildText(Tags.PEER_NAME); int port = Integer.parseInt(rootNode.getChildText(Tags.PORT)); return new ProtocolSignUp(username, port); } else { TagFormatException tfe = new TagFormatException( "It's not a sign up request protocol"); throw tfe; } }
1
private void spawnObstacle() { if (rand.nextInt(100) <= 8) { for (int i = 0; i < 10; i++) { int xPos = rand.nextInt(Game.WIDTH - 30) + 15; Entity o = new EntityObstacle(xPos, 0); if (rand.nextInt(100) <= 2) { o = new EntityObstacleSpecial(xPos, 0); } Object[] e = getCollisionListFor(o).toArray(); if (e.length > 0) { for (int j = 0; j < e.length; j++) { if (!(e[j] instanceof EntityObstacle)) { addEntitiy(o); return; } } } else { addEntitiy(o); return; } } } }
6
public static void nth_number(Integer[] v, Integer n) { int min1 = 0, min2 = 0, min3 = 0; for (Integer value : v) { } }
1
public static int safeLongToInt(long l) { if (l < Integer.MIN_VALUE || l > Integer.MAX_VALUE) { throw new IllegalArgumentException (l + " cannot be cast to int without changing its value."); } return (int) l; }
2
@Override public final void mouseMoved(MouseEvent mouseevent) { int i = mouseevent.getX(); int j = mouseevent.getY(); if (frame != null) { i -= 4; j -= 22; } idleTime = 0; mouseX = i; mouseY = j; }
1
List<CompilationUnit> getMissingCompilationUnits() { List<CompilationUnit> missingCompilationUnits = new ArrayList<>(); compilationUnits.forEach((compilationUnit) -> { try { loadClass(compilationUnit.getName()); } catch (ClassNotFoundException e) { missingCompilationUnits.add(compilationUnit); } }); return missingCompilationUnits; }
1
public TestFrame() { super(new GLTexture("bg0.png",GL13.GL_TEXTURE0)); this.test = new Button(420, 262, Colors.BLUE+"G"+Colors.RED+"o"+Colors.YELLOW+"o"+Colors.BLUE+"g"+Colors.DARKGREEN+"l"+Colors.RED+"e"); this.test.setBackgroundHighlightColor(Colors.VIOLET.getGlColor()); this.test.setBorderColor(Colors.LIGHTSKYBLUE.getGlColor()); this.test.setTooltip("nonsens button"); this.test.addClickListener(new IClickListener(){ @Override public void onClick(int x, int y, MouseButtons button, int grabx, int graby) { l.setText(GLColor.random()+Utility.randomString()); ctest.setPosition(new Random().nextInt(100), new Random().nextInt(100)); }}); this.addComponent(test); this.addComponent(new Button(820, 262, Colors.BLUE+"G"+Colors.RED+" "+Colors.YELLOW+"o"+Colors.BLUE+"g"+Colors.DARKGREEN+"l"+Colors.RED+"e")); this.addComponent(new Button(20, 162, Colors.BLUE+"G"+Colors.RED+"o"+Colors.YELLOW+"o"+Colors.BLUE+"g"+Colors.DARKGREEN+"l"+Colors.RED+"e")); this.ctest = new Button(420, 462, 100, 100, "change background"); this.ctest.setPosition(10, 10); this.ctest.setTooltip("it's kind of magic... well black sorcery"); this.ctest.addClickListener(new IClickListener(){ @Override public void onClick(int x, int y, MouseButtons button, int grabx, int graby) { setRandomBg(); }}); this.ctest.setBorderHighlightColor(Colors.VIOLET.getGlColor()); this.addComponent(ctest); this.l = new Label(150, 10, GLColor.random()+Utility.randomString()); this.addComponent(l); this.md = new Label(340, 140, Mouse.getX()+"/"+Mouse.getY()); this.md.setFontSize(14); this.addComponent(md); this.cbox = new ColorBox(10, 550, 50, 50, GLColor.random()); this.addComponent(cbox); this.ibox = new ImageBox(820, 400, 200, 200, new GLTexture("grid0.png", GL13.GL_TEXTURE0)); this.ibox.setDragable(true); this.ibox.setTooltip("ImageBox, dragable!"); this.addComponent(ibox); this.txt = new TextBox(100, 300, test.getPixelWidth(), 2*test.getPixelHeight(), ""); this.txt.setTooltip("yet another TextBox"); this.addComponent(txt); this.pw = new TextBox(100+test.getPixelWidth()+50, 400, test.getPixelWidth(), test.getPixelHeight(), ""); this.pw.setPasswordMode(true); this.pw.setTooltip("password goes here"); this.addComponent(pw); this.com = new TextBox(420, 10, 700, 60, ""); this.com.setFontSize(30); this.com.setCommandMode(true); this.com.setTooltip("CommandBox"); this.com.addCommandListener(new ICommandListener(){ @Override public void exec(String command) { Cmd.exec(command); }}); this.com.settTGen(new IToolTipGenerator(){ @Override public String[] generateToolTip(String text) { LinkedList<String> ret = new LinkedList<String>(); for(SetKeys s: SetKeys.values()) { if(s.name().toLowerCase().startsWith(text.toLowerCase().split(" ")[0]) && (s.getType() == SettingsType.COMMAND || s.getType() == SettingsType.COMMAND_AND_SETTING|| s.getType() == SettingsType.SETTING)) { if(s.getParameterList() != null) ret.add(s.name().toLowerCase()+" "+ (s.getParameterList().length()>30?s.getParameterList().substring(0,30)+"...":s.getParameterList())+ (s.getDefaultValue()!=null?(" Default value: "+(s.getCls()!=GLColor.class?s.getDefaultValue().toString():((GLColor)s.getDefaultValue()).toReadableString())):"")); //Logger.debug(s.name().toLowerCase()+" "+s.getParameterList()+" Default value: "+(s.getCls()!=GLColor.class?s.getDefaultValue().toString():((GLColor)s.getDefaultValue()).toReadableString())); } } return ret.toArray(new String[1]); }}); this.addComponent(com); this.b = new ProgressBar(420,10+this.com.getPixelHeight()+10,700,50); this.b.setValue(57.378926f); this.b.setTooltip("basically the ProgressBar shows progress"); this.add(b); this.cb = new CheckBox(420,b.getPixelY()+60,"disable CommandBox"); this.cb.setTooltip("dat hook = op"); this.cb.addCheckChangedListener(new ICheckedChangedListener(){ @Override public void onCheckedChange(boolean value) { com.setEnabled(!value); }}); this.cb.setFontSize(20); this.cb.setChecked(true); this.add(cb); this.r1 = new RadioButton(420, cb.getPixelY()+10+cb.getPixelHeight(), "la"); this.r1.setTooltip("dat polygon = op"); this.r1.setFontSize(20); this.add(r1); this.r2 = new RadioButton(420, r1.getPixelY()+10+r1.getPixelHeight(), "li"); this.r2.setTooltip("dat polygon = op"); this.r2.setFontSize(20); this.add(r2); this.r3 = new RadioButton(420, r2.getPixelY()+10+r2.getPixelHeight(), "lu"); this.r3.setTooltip("dat polygon = op"); this.r3.setFontSize(20); this.add(r3); this.ib = new Button(480, cb.getPixelY()+10+cb.getPixelHeight(), "laaaaaaaaaaaaaanger text"); this.ib.setTooltip("me haz icon"); this.ib.setIcon("nut.png"); this.ib.setFontSize(20); this.add(ib); this.tb = new TrackBar(100, 300+this.txt.getPixelHeight()+10, 300, 50); this.tb.setTooltip("Trackbar..."); this.tb.setValue(57.378926f); this.tb.addValueChangeListener(new IFloatListener(){ @Override public void onChange(float value) { b.setValue(value); } }); this.add(tb); }
9
public LinkedList<String[]> getServers() { LinkedList<String[]> servers = new LinkedList<String[]>(); conn.query("SELECT * from "+SCHEMA+".servers"); ResultSet rs = conn.getQueryResult(); try { while( rs.next() ) { servers.add(new String[] { rs.getString("url"), String.valueOf(rs.getInt("server_id")) }); } } catch (SQLException e) { e.printStackTrace(); } conn.closeQuery(); return servers; }
2
public void setLocal(String local) { if(local.length() < 65) { try { isValidLocal(local); this.local = local; } catch(Exception e) { System.out.println(e.getMessage()); System.out.println("Local not set."); } } else System.out.println("Local part length must be less than 65 characters"); }
2
public Vector collide(PhysicsObject a){ Vector aPosition = a.getPosition(); Vector aOldPosition = a.getOldPosition(); Vector aSize = a.getSize(); //System.out.println(aPosition); //if( this.y >= doA.oy + doA.height && (doA.y + doA.height >= this.y) && (doA.x < this.x + this.width && doA.x + doA.width > this.x) ) if( (this.position.y + this.size.y >= aPosition.y) && (this.position.y + this.size.y <= aOldPosition.y) && (aPosition.x + aSize.x > this.position.x && aPosition.x < this.position.x + this.size.x) ){ a.setIsOnGround(true); if( a.getAcceleration().x == 0 ) {aOldPosition.addInPlace(new Vector((aPosition.x - aOldPosition.x)*.0025, 0)); } return new Vector(aPosition.x, this.position.y + this.size.y); } else { //System.out.println("none"); return null; } }
5
@Override public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel) { MOB target=mob; if((auto)&&(givenTarget!=null)&&(givenTarget instanceof MOB)) target=(MOB)givenTarget; if(target.fetchEffect(ID())!=null) { mob.tell(target,null,null,L("<S-NAME> already <S-HAS-HAVE> comprehension.")); return false; } if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; final boolean success=proficiencyCheck(mob,0,auto); if(success) { invoker=mob; final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?L("<T-NAME> feel(s) more comprehending."):L("^S<S-NAME> invoke(s) the power of comprehension!^?")); if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); beneficialAffect(mob,target,asLevel,0); } } else return beneficialWordsFizzle(mob,target,L("<S-NAME> attempt(s) to invoke a spell, but fail(s) miserably.")); // return whether it worked return success; }
8
private static boolean isVowel(char chr){ return (chr == 'A' || chr == 'E' || chr == 'I' || chr == 'O' || chr == 'U' || chr == 'a' || chr == 'e' || chr == 'i' || chr == 'o' || chr == 'u'); }
9
@Override @SuppressWarnings({ "nls", "boxing" }) protected void initialize(Class<?> type, Object oldInstance, Object newInstance, Encoder enc) { super.initialize(type, oldInstance, newInstance, enc); if (type != oldInstance.getClass()) { return; } Menu menu = (Menu) oldInstance; int count = menu.getItemCount(); Expression getterExp = null; for (int i = 0; i < count; i++) { getterExp = new Expression(menu.getItem(i), "getLabel", null); try { // Calculate the old value of the property Object oldVal = getterExp.getValue(); // Write the getter expression to the encoder enc.writeExpression(getterExp); // Get the target value that exists in the new environment Object targetVal = enc.get(oldVal); // Get the current property value in the new environment Object newVal = null; try { newVal = new Expression(((Menu) newInstance).getItem(i), "getLabel", null).getValue(); } catch (IndexOutOfBoundsException ex) { // The newInstance has no elements, so current property // value remains null } /* * Make the target value and current property value equivalent * in the new environment */ if (null == targetVal) { if (null != newVal) { // Set to null Statement setterStm = new Statement(oldInstance, "insert", new Object[] { null, i }); enc.writeStatement(setterStm); } } else { PersistenceDelegate pd = enc .getPersistenceDelegate(targetVal.getClass()); if (!pd.mutatesTo(targetVal, newVal)) { MenuItem menuItem = new MenuItem((String) oldVal); menuItem.setName(menu.getItem(i).getName()); Statement setterStm = new Statement(oldInstance, "add", new Object[] { menuItem }); enc.writeStatement(setterStm); } } } catch (Exception ex) { enc.getExceptionListener().exceptionThrown(ex); } } }
8
@Override public void EntityKilled(Entity entity, Entity killer) { if(entity instanceof Mob){ Mob mob = (Mob)entity; if((killer != null) && (killer instanceof Tower)){ mobGotKilled(mob); ((Tower)killer).kills++; } level.markMobForDeletion(mob); return; } if(entity instanceof Tower){ level.removeTower((Tower)entity); } if(entity instanceof Projectile){ Projectile p = (Projectile)entity; level.markProjectileForDeletion(p); if(p.def.expDef != null){ level.explosions.add(new Explosion(p.loc, p.def.expDef, p.rotation)); if(p.rotation == 0f){ int i = 0; } } } if(entity instanceof Particle){ level.markParticleForDeletion((Particle)entity); } if(entity instanceof Explosion){ level.markExplosionForDeletion((Explosion)entity); } }
9
public Locale dequeue() throws Exception { Locale retVal = null; // Check for underflow. if (!this.isEmpty()) { retVal = arr[frontPtr]; // Shift every element towards the front. for (int i = 0; i < backPtr; i++) { arr[i] = arr[i + 1]; } // Reinitialize the last element arr[backPtr] = null; // shift the back pointer towards the front. backPtr--; } else { // In case of underflow, throw an underflow exception. throw new Exception(); } return retVal; }
2
public <T> void registerMethods(final Class<T> cls, String toStringMethodName, String fromStringMethodName) { if (cls == null) { throw new IllegalArgumentException("Class must not be null"); } if (toStringMethodName == null || fromStringMethodName == null) { throw new IllegalArgumentException("Method names must not be null"); } if (this == INSTANCE) { throw new IllegalStateException("Global singleton cannot be extended"); } Method toString = findToStringMethod(cls, toStringMethodName); Method fromString = findFromStringMethod(cls, fromStringMethodName); MethodsStringConverter<T> converter = new MethodsStringConverter<T>(cls, toString, fromString, cls); registered.putIfAbsent(cls, converter); }
4
public Value( String strVal ) { value = strVal; // test to see which type of value it is if ( value.compareTo("#t") == 0 || value.compareTo("#f") == 0) { type = "boolean"; } else if ( value.matches("-?\\d+") ) { type = "integer"; } else if ( value.matches("-?\\d*.\\d+") ) { type = "decimal"; } else if ( value.startsWith("\"") && value.endsWith("\"") ) { type = "string"; } else { // you should never get here if called from interp() System.err.println("Error in Value Constructor: Unknown Type '" + strVal + "'"); type = "undefined"; } }
6
private static void initChoiceCombinationAndChoices() { if (choiceCombination == null || choiceCombination.length == 0) { return; } indexsArray = new Integer[choiceCombination.length]; for (int i = 0; i < choiceCombination.length; i++) { indexsArray[i] = i; String itemString = choiceCombination[i]; if (itemString == null || itemString.length() == 0) { continue;// FIXME should throw exception to make sure index is consistent with ChoiceCombination. } char[] chars = itemString.toCharArray(); List<Choice> choiceList = new ArrayList<Choice>(); for (int j = 0; j < chars.length; j++) { Choice choice = new Choice(String.valueOf(chars[j])); choiceList.add(choice); } choiceCombinationMap.put(i, choiceList); } }
6
public static void printResult(Map<String, Double> result, ArgumentValidator validator, int limit) { try { FileWriter fstream = null; BufferedWriter out = null; boolean writeToFile = validator.getSearchOut() == null ? false : true; // Create file if (writeToFile) { fstream = new FileWriter(new File(validator.getSearchOut())); out = new BufferedWriter(fstream); } DecimalFormat df = new DecimalFormat("0.##E0"); //df.setMaximumFractionDigits(2); int i = 0; for (String doc : result.keySet()) { if (i == limit) break; if (writeToFile) { out.write("topic" + validator.getTopicNumber() + " Q0 " + doc + " " + (i+1) + " " + df.format(result.get(doc)) + " group1_" + validator.getListSize()+"\n"); } else { System.out.printf("topic%d Q0 %s %d %s groupA_%s\n", validator.getTopicNumber(), doc, i + 1, df.format(result.get(doc)), validator.getListSize()); } i++; } if (writeToFile) { out.close(); logger.info("Wrote search results to " + validator.getSearchOut()); } } catch (Exception e) { logger.error("Search failed :/", e); } }
7
private static String rationalPartFrom(String expression, int part) { notNull(expression, "Expression cannot be null"); int p = expression.indexOf("/"); switch (part) { case NUMERATOR: return p > 0 ? expression.substring(0, p) : expression; case DENOMINATOR: return p > 0 ? expression.substring(p + 1) : "1"; default: throw new IllegalArgumentException("Unknown part type"); } }
4
public Object [][] getDatos(){ Object[][] data = new String[getCantidad_Cuentas ()][colum_names.length]; //realizamos la consulta sql y llenamos los datos en "Object" try{ if (colum_names.length>=0){ r_con.Connection(); String campos = colum_names[0]; for (int i = 1; i < colum_names.length; i++) { campos+=","; campos+=colum_names[i]; } String consulta = ("SELECT "+campos+" "+ "FROM "+name_tabla+" WITH (INDEX("+indices_tabla[numero_ordenamiento_elegido]+"))"); PreparedStatement pstm = r_con.getConn().prepareStatement(consulta); ResultSet res = pstm.executeQuery(); int i = 0; while(res.next()){ for (int j = 0; j < colum_names.length; j++) { data[i][j] = res.getString(j+1); } i++; } res.close(); } } catch(SQLException e){ System.out.println(e); } finally { r_con.cierraConexion(); } return data; }
5
public static synchronized DatabaseConnection getInstance(){ if (DatabaseConnection.instance == null){ DatabaseConnection.instance = new DatabaseConnection(); } return DatabaseConnection.instance; }
1
public boolean fGuiCheckChildObjectNonExistence(WebElement objParent, String strDesc){ //Delimiters String[] delimiters = new String[] {":="}; String[] arrFindByValues = strDesc.split(delimiters[0]); //Get Findby and Value String FindBy = arrFindByValues[0]; String val = arrFindByValues[1]; //WebElement Collection List<WebElement> lst; try { //Handle all FindBy cases String strElement = FindBy.toLowerCase(); if (strElement.equalsIgnoreCase("linktext")) { lst = objParent.findElements(By.linkText(val)); } else if (strElement.equalsIgnoreCase("xpath")) { lst = objParent.findElements(By.xpath(val)); } else if (strElement.equalsIgnoreCase("name")) { lst = objParent.findElements(By.name(val)); } else if (strElement.equalsIgnoreCase("id")) { lst = objParent.findElements(By.id(val)); } else if (strElement.equalsIgnoreCase("classname")) { lst = objParent.findElements(By.className(val)); } else if (strElement.equalsIgnoreCase("cssselector")) { lst = objParent.findElements(By.cssSelector(val)); } else if (strElement.equalsIgnoreCase("tagname")) { lst = objParent.findElements(By.tagName(val)); } else { Reporter.fnWriteToHtmlOutput("Check object Non Existence for child object " + strDesc, "Object should not exist", "Property " + FindBy + " specified for object is invalid", "Fail"); System.out.println("Property name " + FindBy + " specified for object " + strDesc + " is invalid"); return false; } if(lst.size() == 0) { Reporter.fnWriteToHtmlOutput("Check Non Existence of child object " + strDesc, "Object Should not exist", "Object does not exist", "Pass"); return true; } else { Reporter.fnWriteToHtmlOutput("Check Non Existence of child object " + strDesc, "Object Should not exist", "Object exist", "Fail"); return false; } } //Catch Block catch(Exception e) { Reporter.fnWriteToHtmlOutput("Check Non Existence of child object " + strDesc, "Object should not exist", "Exception occured while checking existence", "Fail"); System.out.println("Exception " + e.toString() + " occured while checking object non existence"); return false; } }
9
public double getSternCapPerSquareMetre(){ if(!this.sternOption){ System.out.println("Class: GouyChapmanStern\nMethod: getSternCapacitance\nThe Stern modification has not been included"); System.out.println("A value of infinity has been returned"); return Double.POSITIVE_INFINITY; } if(this.psi0set && this.sigmaSet){ return this.sternCap; } else{ if(this.sigmaSet){ this.getSurfacePotential(); return this.sternCap; } else{ if(this.psi0set){ this.getSurfaceChargeDensity(); return this.sternCap; } else{ System.out.println("Class: GouyChapmanStern\nMethod: getSternCap\nThe value of the Stern capacitance has not been calculated\ninfinity returned"); System.out.println("Neither a surface potential nor a surface charge density have been entered"); return Double.POSITIVE_INFINITY; } } } }
5
public void setTable() { // Centering the first two column's cell content DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer(); centerRenderer.setHorizontalAlignment(JLabel.CENTER); questionTable.getColumnModel().getColumn(0).setCellRenderer(centerRenderer); questionTable.getColumnModel().getColumn(1).setCellRenderer(centerRenderer); // Set the columns width TableColumn column = null; for (int i = 0; i < 3; i++) { column = questionTable.getColumnModel().getColumn(i); if (i == 0) { column.setPreferredWidth(69); //sport column is bigger } else if (i == 1) { column.setPreferredWidth(164); } else { column.setPreferredWidth(800); } } }
3
private void readStudents(Element node, Group group) throws ServerException { if (log.isDebugEnabled()) log.debug("Method call. Arguments: " + group); Element studentsNode = (Element) node.getElementsByTagName("students") .item(0); if (studentsNode == null) { ServerException ex = new ServerException( "Can't read student from group " + group.getNumber()); log.error("Exception", ex); throw ex; } NodeList students = studentsNode.getElementsByTagName("student"); try { for (int i = 0; i < students.getLength(); i++) { NamedNodeMap attributes = students.item(i).getAttributes(); Student student = new Student(); student.setEnrolled(attributes.getNamedItem("enrolled") .getTextContent()); student.setFirstName(attributes.getNamedItem("firstname") .getTextContent()); student.setGroupNumber(attributes.getNamedItem("groupnumber") .getTextContent()); student.setId(new Integer(attributes.getNamedItem("id") .getTextContent())); student.setLastName(attributes.getNamedItem("lastname") .getTextContent()); group.addStudent(student); } } catch (NumberFormatException e) { ServerException ex = new ServerException("Wrong id in database", e); log.error("Exception", ex); throw ex; } catch (DOMException e) { ServerException ex = new ServerException("Database reading error!", e); log.error("Exception", ex); throw ex; } catch (ParseException e) { ServerException ex = new ServerException("Database reading error!", e); log.error("Exception", ex); throw ex; } }
6
public static void main(String[] args) throws SummerMissingException { Programmetajs programmetajs = new Programmetajs(); Vasara vasara = new Vasara(); programmetajs.Vards = "Janis"; vasara.VidejaTemperatura = 20; if (vasara.VidejaTemperatura < 20) throw new SummerMissingException(":("); Random random = new Random(441287210); int sodienasTemperatura = random.nextInt(10)*30; if (sodienasTemperatura > vasara.VidejaTemperatura) { programmetajs.PrasitAtvalinajumu = true; programmetajs.Atvalinajums = new Atvalinajums() {{ DienuSkaits = 15; BrauciensArpusLatvijas = true; }}; } else { programmetajs.PrasitAtvalinajumu = false; } String brauciens = programmetajs.PrasitAtvalinajumu ? "dosies arpus Latvijas " + programmetajs.Atvalinajums.DienuSkaits + " dienu atvalinajuma" : "paliks darba"; System.out.println(programmetajs.Vards + " " + brauciens); }
3
public static long getLastUpdate(){ Connection con = DBase.dbConnection(); PreparedStatement pst; long t=0; Calendar c = Calendar.getInstance(); try{ String query = "Select Distinct RetreiveDate FROM \"ME\".USD"; pst = con.prepareStatement(query); ResultSet rs = pst.executeQuery(); while(rs.next()){ c.setTime(rs.getTimestamp(1)); t = c.getTimeInMillis(); } pst.close(); con.close(); }catch(SQLException e){System.err.println(e);} return t; }
2
void getPreviousWavelength (){ previousStateValues = FileManager.loadBackup(); if(Integer.parseInt(previousStateValues.get(0)) == -1){ previousStateValues.set(0, "0"); } if(Integer.parseInt(previousStateValues.get(1)) == -1){ previousStateValues.set(1, "0"); } int conversion1 = Integer.parseInt(previousStateValues.get(0)); int conversion2 = Integer.parseInt(previousStateValues.get(1)); System.out.println(conversion1); System.out.println(conversion2); comboLaser1.setSelectedIndex(conversion1); comboLaser2.setSelectedIndex(conversion2); if(("" + comboLaser1.getSelectedItem()).compareTo("Wavelength L1") != 0 && ("" + comboLaser2.getSelectedItem()).compareTo("Wavelength L2") != 0){ System.out.println("" + comboLaser1.getSelectedItem()); double[] lecture1; double[] lecture2; lecture1 = FileManager.readValues(("" + comboLaser1.getSelectedItem()).replaceFirst(" nm", ".ml1"), 1); lecture2 = FileManager.readValues(("" + comboLaser2.getSelectedItem()).replaceFirst(" nm", ".ml2"), 2); for(int l = 0; l < 11; l++){ calibrationLaser1[l] = lecture1[l]; calibrationLaser2[l] = lecture2[2]; } calibrationMemorised = true; sliderLaser1.setVisible(true); sliderLaser2.setVisible(true); labelSliderLaser1.setVisible(true); labelSliderLaser2.setVisible(true); labelPointNumber.setVisible(true); buttonAdd.setVisible(true); buttonRemove.setVisible(true); buttonRemoveAll.setVisible(true); updateConsole(); } allowBackupUpdate = true; }
5
public String exportCustReport() { File outFile = new File(STAFF_REPORT_PATH); if(outFile.exists()){ outFile.delete(); } IDataVector<ISubDataVector> data = Application.RECORD_VIEW.getTableModel().getData(); FileInputStream in = null; OutputStream out = null; try { in = new FileInputStream(new File("res/template/cust_report.xls")); HSSFWorkbook hwb = new HSSFWorkbook(in); HSSFSheet hst = hwb.getSheetAt(0); int row = 1; for (ISubDataVector sub : data) { RecordSubVector s = (RecordSubVector)sub; String qrCode = s.getQrCode(); String name = s.getName(); String salutaion = s.getSalutaion(); HSSFRow hrw = hst.createRow(row ++); hrw.createCell(0).setCellValue(qrCode); hrw.createCell(1).setCellValue(name); hrw.createCell(2).setCellValue(salutaion); boolean isFirstRow = true; SeeMoreDataVector moreInfo = s.getMoreInfo(); for (ISubDataVector subMore : moreInfo) { SeeMoreSubVector m = (SeeMoreSubVector)subMore; Date date = m.getDate(); SimpleDateFormat smfDate = new SimpleDateFormat("yyyy/M/d"); String dateStr = smfDate.format(date); SimpleDateFormat smfTime = new SimpleDateFormat("HH:mm:ss"); String timeStr = smfTime.format(date); if(isFirstRow){ hrw.createCell(3).setCellValue(dateStr); hrw.createCell(4).setCellValue(timeStr); isFirstRow = false; }else{ hrw = hst.createRow(row ++); hrw.createCell(3).setCellValue(dateStr); hrw.createCell(4).setCellValue(timeStr); } } hrw = hst.createRow(row ++); } out = new FileOutputStream(CUST_REPORT_PATH); hwb.write(out); } catch (IOException e) { e.printStackTrace(); }finally{ if(in != null){ try { in.close(); } catch (IOException e) { e.printStackTrace(); } } if(out != null){ try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } return CUST_REPORT_PATH; }
9
public void setNametextFontcolor(int[] fontcolor) { if ((fontcolor == null) || (fontcolor.length != 4)) { this.nametextFontColor = UIFontInits.NAME.getColor(); } else { this.nametextFontColor = fontcolor; } somethingChanged(); }
2
public void bOpen(){ if (isOpen) return; if (bombsBeingRevealed && getValue() != 9){ return; } if (markIndex > 0){ return; } if (!hasStarted) MainFrame.startTimer(); getModel().setPressed(true); getModel().setEnabled(false); isOpen = true; chooseIcon(true); //theGame.openSpot(xPos, yPos); }
5
private void initFenetre() { this.setLocationRelativeTo(null); this.setUndecorated(true); this.setResizable(false); this.setSize(350, 200); JLabel finJeuLabel = new JLabel(); finJeuLabel.setIcon(new ImageIcon(getClass().getClassLoader().getResource("popupLabel.jpg"))); finJeuLabel.setLayout(new FlowLayout()); JButton nivSuivant = new JButton(new ImageIcon(getClass().getClassLoader().getResource("niveauSuivantButton.jpg"))); nivSuivant.setPreferredSize(new Dimension(120, 45)); JButton reessayer = new JButton(new ImageIcon(getClass().getClassLoader().getResource("reessayerButton.jpg"))); reessayer.setPreferredSize(new Dimension(100, 45)); JButton menu = new JButton(new ImageIcon(getClass().getClassLoader().getResource("menuButton.jpg"))); menu.setPreferredSize(new Dimension(85, 45)); this.setContentPane(finJeuLabel); this.add(Box.createRigidArea(new Dimension(0,250))); if(Joueur.isModeSolo() == false) { if(Niveau.getNbNiveauxCrees() <= niveauFini){ this.setVisible(false); ecranJeu.setVisible(false); int scoreAutreJoueur = 0; if(Joueur.isHost()){ try { ServeurBubbleBlast.ecrireScoreSocket(); scoreAutreJoueur = ServeurBubbleBlast.lireScoreSocket(); EcranResultats ecranResultats = new EcranResultats(scoreAutreJoueur); ecranResultats.setVisible(true); } catch (Exception e) {} } else{ try { ClientBubbleBlast.ecrireScoreSocket(); scoreAutreJoueur = ClientBubbleBlast.lireScoreSocket(); EcranResultats ecranResultats = new EcranResultats(scoreAutreJoueur); ecranResultats.setVisible(true); } catch (Exception e) {} } } } else if(niveauFini >= Niveau.getNbNiveauxCrees()) { nivSuivant.setVisible(false); this.add(Box.createRigidArea(new Dimension(124,45))); } this.add(nivSuivant); if(Joueur.isModeSolo() == false) { reessayer.setVisible(false); this.add(Box.createRigidArea(new Dimension(100,45))); } this.add(reessayer); this.add(menu); nivSuivant.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { jButtonNivSuivantActionPerformed(evt); } }); reessayer.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { jButtonReessayerActionPerformed(evt); } }); menu.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { jButtonMenuActionPerformed(evt); } }); }
7
public Inventory solveGreedily() { int availableCapacity = capacity; ArrayList<Double> amounts = new ArrayList<Double>(); if (availableCapacity <= 0) { return new Inventory(this, amounts); } for (Item i : items) { if (availableCapacity < i.getWeight()) { amounts.add(0.0); } else { availableCapacity -= i.getWeight(); amounts.add(1.0); } } return new Inventory(this, amounts); }
3
public void play(File file) { if (stopRequested) { stopRequested = false; try { AudioInputStream stream = AudioSystem.getAudioInputStream(file); AudioFormat format = stream.getFormat(); DataLine.Info info = new DataLine.Info(Clip.class, stream.getFormat(), ((int) stream.getFrameLength() * format.getFrameSize())); clip = (Clip) AudioSystem.getLine(info); if (listeners != null) { for (LineListener l : listeners) clip.addLineListener(l); } clip.open(stream); // This method does not return until the audio file is completely loaded } catch (IOException e) { e.printStackTrace(); } catch (LineUnavailableException e) { e.printStackTrace(); } catch (UnsupportedAudioFileException e) { e.printStackTrace(); } } if (clip != null) clip.start(); }
7
protected void execute() { // TODO Auto-generated method stub double speed = scale(oi.getXSpeed(RobotMap.HookController)); if(speed > 0 && !hookMotors.Limit1.get()){ hookMotors.motor1.set(speed); } else if(speed < 0 && !hookMotors.Limit2.get()){ hookMotors.motor2.set(-speed); } }
4
private final void method3167(int i, ByteBuffer class348_sub49, byte i_2_) { if (i_2_ == -86) { anInt9489++; if ((i ^ 0xffffffff) == -250) { int i_3_ = class348_sub49.getUByte(); if (aClass356_9494 == null) { int i_4_ = Class33.method340(i_3_, (byte) 108); aClass356_9494 = new HashTable(i_4_); } for (int i_5_ = 0; (i_3_ ^ 0xffffffff) < (i_5_ ^ 0xffffffff); i_5_++) { boolean bool = class348_sub49.getUByte() == 1; int i_6_ = class348_sub49.getTri(); Node class348; if (bool) class348 = new StringNode(class348_sub49 .getJstr()); else class348 = new Class348_Sub35(class348_sub49 .getDword()); aClass356_9494.putNode((long) i_6_, class348); } } } }
5
public static void doLevel() throws ClassNotFoundException, FileNotFoundException, IOException, InterruptedException { addToPattern(); SimoneUI.blinker.run(); Thread.sleep(5000); for(Integer i: currentPattern) { // Don't need the integer, but it will ask for the same number of inputs as are in the current pattern if (i!=returnedindex){ cont = false; break; } } if (cont) { currentplayer.incrementCurrentLevel(); doLevel(); } else { currentplayer.setScore(computeScore()); HighScore.processScore(currentplayer); } }
3
public void executarMetodos() throws MyClassException { SingleValueVetor obj = new SingleValueVetor(); for (Method metodo : obj.getClass().getDeclaredMethods()) { for (Annotation anotacao : metodo.getAnnotations()) { if ((anotacao instanceof SingleValueLogAnnotation) && (((SingleValueLogAnnotation) anotacao).gravarLog() == true)) { try { System.out.println("Gravando Log do início da execução"); // metodo processado é o método carregarVetor(). if (metodo.getName().equals("carregarVetor")) { System.out.println("Método carregarVetor()"); System.out.println(new Date()); metodo.invoke(obj, new Object[]{new Vector<String>()}); } else { if (metodo.getName().equals("dormir")) { System.out.println("Método dormir()"); System.out.println(new Date()); metodo.invoke(obj); } } System.out.println(new Date()); System.out.println("Gravando Log do fim da execução"); System.out.println(); } catch (IllegalArgumentException e) { MyClassException m = new MyClassException("Exceção capturada: IllegalArgumentException"); m.setMensagem(e.getMessage()); throw m; } catch (IllegalAccessException e) { MyClassException m = new MyClassException( "Exceção capturada: IllegalAccessException"); m.setMensagem(e.getMessage()); throw m; } catch (InvocationTargetException e) { MyClassException m = new MyClassException( "Exceção capturada: InvocationTargetException"); m.setMensagem(e.getMessage()); throw m; } } } } }
9
@Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; }
1
public void startTreasureHunt() { found = false; if(currentTreasureLocation != null && currentTreasureLocation.getBlock().getType().equals(Material.CHEST)) { Chest chest = (Chest)currentTreasureLocation.getBlock().getState(); Inventory inv = chest.getBlockInventory(); inv.clear(); currentTreasureLocation.getBlock().setType(Material.AIR); } if(possibleTreasures.size() == 0 || possibleLocations.size() == 0) { TreasureHunt.getInstance().getLogger().log(Level.INFO, "No treasures or locations"); return; } TreasureHunt.getInstance().getServer().broadcastMessage(ChatColor.GREEN + "Treasure Hunt is beginning! type '/th info' for the location of the treasure chest."); int index = randomGenerator.nextInt(possibleTreasures.size()); currentTreasure = possibleTreasures.get(index); TreasureHunt.getInstance().getLogger().log(Level.INFO, "Treasure: " + index); randomGenerator = new Random(); index = randomGenerator.nextInt(possibleLocations.size()); currentTreasureLocation = possibleLocations.get(index); TreasureHunt.getInstance().getLogger().log(Level.INFO, "Location: " + index); currentTreasureLocation.getBlock().setType(Material.CHEST); Chest chest = (Chest)currentTreasureLocation.getBlock().getState(); Inventory inv = chest.getBlockInventory(); for(int i = 0; i < currentTreasure.getLoot().size(); i++) { inv.setItem(i, currentTreasure.getLoot().get(i)); } }
5
final void method1092(int i, int i_0_) { anInt1819++; for (int i_1_ = 0; ((Model) this).vertices > i_1_; i_1_++) { ((Model) this).vertexX[i_1_] <<= i; ((Model) this).vertexY[i_1_] <<= i; ((Model) this).vertexZ[i_1_] <<= i; } if (i_0_ <= 39) method1107(40, -7, -80, -24); if ((((Model) this).anInt1818 ^ 0xffffffff) < -1 && ((Model) this).anIntArray1859 != null) { for (int i_2_ = 0; i_2_ < ((Model) this).anIntArray1859.length; i_2_++) { ((Model) this).anIntArray1859[i_2_] <<= i; ((Model) this).anIntArray1816[i_2_] <<= i; if ((((Model) this).aByteArray1823[i_2_] ^ 0xffffffff) != -2) ((Model) this).anIntArray1844[i_2_] <<= i; } } }
6
private void setUsersState(int state){ //Номер колонки айди пользователя final int columnId = 0; //Если выбран пользователь в таблице if (tableUsers.getSelectedRow() != -1) { //Получаем идентификатор выбранного пользователя int userId = (Integer)tableUsers.getValueAt(tableUsers.getSelectedRow(), columnId); Statement statement = null; ResultSet result = null; try { statement = usersDAO.getConnection().createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); result = statement.executeQuery(usersDAO.getAllQuery()); //Находим запись по айди while (result.next()) { if (result.getInt("ID") == userId) { break; } } //Устанавливаем статус пользователя result.updateInt("USERSTATE", state); //Обновляем запись result.updateRow(); //Обновляем таблицу usersDAO = new UsersDAO(); usersDAO.initTableModel(tableUsers, usersDAO.listAll()); } catch (SQLException exc) { JOptionPane.showMessageDialog(this, "Ошибка при обновлении данных"); } } else { JOptionPane.showMessageDialog(this, "Не выбран пользователь в таблице!"); return; } }
4
public static long parseTimeInterval(String str) { try { int len = str.length(); char suffix = str.charAt(len - 1); String numstr; long mult = 1; if (Character.isDigit(suffix)) { numstr = str; } else { numstr = str.substring(0, len - 1); switch (Character.toUpperCase(suffix)) { case 'S': mult = Constants.SECOND; break; case 'M': mult = Constants.MINUTE; break; case 'H': mult = Constants.HOUR; break; case 'D': mult = Constants.DAY; break; case 'W': mult = Constants.WEEK; break; default: throw new NumberFormatException("Illegal time interval suffix"); } } return Long.parseLong(numstr) * mult; } catch (IndexOutOfBoundsException e) { throw new NumberFormatException("empty string"); } }
7
public static Model getModel(int id) { if (Model.modelHeaderCache == null) { return null; } ModelHeader modelHeader = Model.modelHeaderCache[id]; if (modelHeader == null) { Model.fileRequester.get(id); return null; } else { return new Model(id); } }
2
private void dehighlight() { pane.tablePanel.dehighlight(); pane.grammarTable.dehighlight(); pane.tablePanel.repaint(); pane.grammarTable.repaint(); }
0
private static String applyUnification(String sen1, String sen2, String[][] substitution){ String newSentence = ""; for(int i = 1; i < substitution.length; i++){ if(substitution[i][0] != null){ sen1 = sen1.replaceAll(substitution[i][0], substitution[i][1]); sen2 = sen2.replaceAll(substitution[i][0], substitution[i][1]); } } //clean up the clauses if(sen1.length() < sen2.length()){ sen2 = sen2.replace(sen1, ""); sen2 = sen2.replace("&&", "&"); sen2 = sen2.replace("&|", "|"); if(sen2.charAt(0) == '&'){ sen2 = sen2.substring(1,sen2.length()); } if(sen2.charAt(sen2.length() - 1) == '|'){ sen2 = sen2.substring(0, sen2.length() - 1); } newSentence = sen2; } else{ sen1 = sen1.replace(sen2, ""); sen1 = sen1.replace("&&", "&"); sen1 = sen1.replace("&|", "|"); if(sen1.charAt(0) == '&'){ sen1 = sen1.substring(1,sen1.length()); } if(sen1.charAt(sen1.length() - 1) == '|'){ sen1 = sen1.substring(0, sen1.length() - 1); } newSentence = sen1; } newSentence = doMath(newSentence); return newSentence; }
7
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(InterfazReproductor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(InterfazReproductor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(InterfazReproductor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(InterfazReproductor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new InterfazReproductor().setVisible(true); } }); }
6
public void wanderSpawner(){ if(time % 10 + random.nextInt(25) == 0) pickWanderLocation(); if(targetX != 0 && targetY != 0) pathTo(new Vector2i(x / 32, y / 32), new Vector2i(targetX, targetY), 0); }
3
private Position findPlayer(ArrayList<String> board) throws Exception { for (int y = 0; y < board.size(); ++y) { for (int x = 0; x < board.get(y).length(); ++x) { char c = board.get(y).charAt(x); if (c == '@' || c == '+') return new Position(x, y); } } throw new Exception("Could not find the player in the board"); }
4
private void copyNsAndAttributes(XMLStreamReader parser, XMLStreamWriter writer) throws XMLStreamException { int nbNamespace = parser.getNamespaceCount(); for (int i = 0; i < nbNamespace; i++) { String nsPrefix = parser.getNamespacePrefix(i); String nsURI = parser.getNamespaceURI(i); // Workaround gcj bug // See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=40653 try { if (nsPrefix == null || "".equals(nsPrefix)) { writer.writeDefaultNamespace(nsURI); } else { writer.writeNamespace(nsPrefix, nsURI); } } catch (IllegalArgumentException ignore) { } } int nbAttributes = parser.getAttributeCount(); for (int i = 0; i < nbAttributes; i++) { String attrNamespace = parser.getAttributeNamespace(i); String attrPrefix = parser.getAttributePrefix(i); String attrName = parser.getAttributeLocalName(i); String value = parser.getAttributeValue(i); // Workaround gcj bug // See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=40653 if (attrNamespace == null) { writer.writeAttribute(attrName, value); } else { writer.writeAttribute(attrPrefix, attrNamespace, attrName, value); } } }
6
@Override public void setup( BSPPeer<NullWritable, NullWritable, NullWritable, NullWritable, JobMessage> peer) throws IOException, SyncException, InterruptedException { HamaConfiguration conf = peer.getConfiguration(); blockSize = conf.getInt(blockSizeString, 2); /* Values for rows and columns padded */ nbRowsA = Utils.getBlockMultiple(conf.getInt(inputMatrixARows, 4), blockSize); nbColsA = Utils.getBlockMultiple(conf.getInt(inputMatrixACols, 4), blockSize); nbRowsB = Utils.getBlockMultiple(conf.getInt(inputMatrixBRows, 4), blockSize); nbColsB = Utils.getBlockMultiple(conf.getInt(inputMatrixBCols, 4), blockSize); a = new Matrix(Utils.readMatrix( new Path(conf.get(inputMatrixAPathString)), peer.getConfiguration(), conf.getInt(inputMatrixARows, 4), conf.getInt(inputMatrixACols, 4), blockSize), nbRowsA, nbColsA); b = new Matrix(Utils.readMatrix( new Path(conf.get(inputMatrixBPathString)), peer.getConfiguration(), conf.getInt(inputMatrixBRows, 4), conf.getInt(inputMatrixBCols, 4), blockSize), nbRowsB, nbColsB); if (peer.getPeerIndex() == 0) { /* * System.out.println("A"); a.print(); System.out.println("B"); * b.print(); System.out.println("A*B"); * System.out.println(a.mult(b).toString()); */ int peerInd = 0; indices = new HashMap<Integer, List<Integer[]>>(); for (int i = 0; i < nbRowsA / blockSize; i++) { for (int j = 0; j < nbColsB / blockSize; j++) { for (int k = 0; k < nbColsA / blockSize; k++) { if (peerInd == 0) { if (masterIndices == null) { masterIndices = new ArrayList<Integer[]>(); } masterIndices.add(new Integer[] { i, j, k }); } else { JobMessage job = new JobMessage(0, i, j, k); peer.send(peer.getPeerName(peerInd), job); } List<Integer[]> peerIndices = indices.get(peerInd); if (peerIndices == null) { peerIndices = new ArrayList<Integer[]>(); } peerIndices.add(new Integer[] { i, j }); indices.put(peerInd, peerIndices); peerInd = (peerInd + 1) % peer.getNumPeers(); } } } } peer.sync(); }
7
public void make_pivot(ArrayList<finger_print> outliers){ ////System.out.println("Total outliers :" +outliers.size()); if(outliers.size()< OUTLIERS_SIZE || outliers.size() < PIVOT_SIZE_TOTAL){ for(int i=0;i<outliers.size();i++){ final_pivot_list.add(new node(outliers.get(i))); } return; } ArrayList<node> pivot_lst= new ArrayList<node>(); Random r= new Random(); for(int i=0;i<PIVOT_SIZE_TOTAL;i++){ int j=r.nextInt(outliers.size()); pivot_lst.add(new node(outliers.get(j))); outliers.remove(j); } if(outliers.size()==0) { final_pivot_list.addAll(pivot_lst); return; } for(finger_print p : outliers){ p.set_sim_pivot(pivot_lst); } Collections.sort(outliers); double median_similarity = getMedian_sim(outliers); for(int i=outliers.size()/2 -1;i<outliers.size();i++){ if(outliers.get(i).getSim_closest_pivot() > median_similarity){ for(int j=outliers.size()-1;j>=i;j--){ outliers.get(j).getClosest_pivot().set_object(outliers.get(j)); outliers.remove(j); } break; } } final_pivot_list.addAll(pivot_lst); node outlier_pvt=new node(outliers); final_pivot_list.add(outlier_pvt); outlier_pvt.setOutlier_pivot(true); make_pivot(outliers); return; }
9
private MinesNode[] getSurroundingNodes(int inX, int inY) { Vector v = new Vector(); for (int i = (inX-1); i <= (inX+1); i++) { for (int j = (inY-1); j <= (inY+1); j++) { if (i >= 0 && j >= 0 && i < width && j < height && !(i == inX && j == inY)) v.addElement(minesNodes[i][j]); } } MinesNode[] result = new MinesNode[v.size()]; for (int i = 0; i < result.length; i++) { result[i] = (MinesNode)v.elementAt(i); } return result; }
9
public static boolean isValidSuggestion(Suggestion s) { if (s.getSubject().isEmpty()) { return false; } if (s.getDescription().isEmpty()) { return false; } if (!UserModel.isValidUser(s.getAuthor())) { return false; } System.out.println("This is a valid suggestion"); return true; }
3
public int[][] directHoaar(int f[][]) { int c[] = zigZag.getHideZigZagArray(f, N); int result[] = new int[N * N]; for (int i = 0; i < N * N / 2; i++) { result[2 * i] = ((c[2 * i] + c[2 * i + 1])); result[2 * i + 1] = ((c[2 * i] - c[2 * i + 1])); } int array[][] = zigZag1.getIntegerArray(result); // there was c return array; }
1
public void reloadAll() { Class<Textures> localTextures = Textures.class; BufferedImage localBufferedImage1; for (Iterator localIterator = this.loadedImages.keySet().iterator(); localIterator.hasNext(); ) { int i = ((Integer)localIterator.next()).intValue(); localBufferedImage1 = (BufferedImage)this.loadedImages.get(i); loadTexture(localBufferedImage1, i); } Iterator<String> localIterator; for (localIterator = this.idMap.keySet().iterator(); localIterator.hasNext(); ) { String str = (String)localIterator.next(); try { localBufferedImage1 = readImage(localTextures.getResourceAsStream(str)); int j = ((Integer)this.idMap.get(str)).intValue(); loadTexture(localBufferedImage1, j); this.blur = false; this.clamp = false; } catch (IOException localIOException1) { localIOException1.printStackTrace(); } } String str; for (localIterator = this.pixelsMap.keySet().iterator(); localIterator.hasNext(); ) { str = (String)localIterator.next(); try { BufferedImage localBufferedImage2 = readImage(localTextures.getResourceAsStream(str)); loadTexturePixels(localBufferedImage2, (int[])(int[])this.pixelsMap.get(str)); this.blur = false; this.clamp = false; } catch (IOException localIOException2) { localIOException2.printStackTrace(); } } }
5
private double leastSquares(Instances instances) { double numerator=0, denominator=0, w, t; double[] classMeans = new double[m_numOfClasses]; double[] classTotals = new double[m_numOfClasses]; for (int i=0; i<instances.numInstances(); i++) { LADInstance inst = (LADInstance) instances.instance(i); for (int j=0; j<m_numOfClasses; j++) { classMeans[j] += inst.zVector[j] * inst.wVector[j]; classTotals[j] += inst.wVector[j]; } } double numInstances = (double) instances.numInstances(); for (int j=0; j<m_numOfClasses; j++) { if (classTotals[j] != 0) classMeans[j] /= classTotals[j]; } for (int i=0; i<instances.numInstances(); i++) for (int j=0; j<m_numOfClasses; j++) { LADInstance inst = (LADInstance) instances.instance(i); w = inst.wVector[j]; t = inst.zVector[j] - classMeans[j]; numerator += w * (t * t); denominator += w; } //System.out.println(numerator + " / " + denominator); return numerator > 0 ? numerator : 0;// / denominator; }
7
public void setPieces(){ TicTacToePiece[][] piecesToBeSaved = TicTacToeBoard.getBoard(); for(int j = 0; j < piecesToBeSaved[0].length; j++){ for(int i = 0; i < piecesToBeSaved.length; i++){ if(piecesToBeSaved[i][j].getPieceColour() == Piece.TicTacToePieceColour.NOUGHT){ Element newNoughtPiece; System.out.println(Game.getPlayer(0).getColour()); if(Game.getPlayer(0).getColour().equals(Piece.TicTacToePieceColour.NOUGHT)){ newNoughtPiece = getDoc().createElement("piece1"); }else{ newNoughtPiece = getDoc().createElement("piece2"); } Element x = getDoc().createElement("x"); x.appendChild(getDoc().createTextNode(i + "")); Element y = getDoc().createElement("y"); y.appendChild(getDoc().createTextNode(j + "")); newNoughtPiece.appendChild(x); newNoughtPiece.appendChild(y); if(Game.getPlayer(0).getColour().equals(Piece.TicTacToePieceColour.NOUGHT)){ getPlayers(0).appendChild(newNoughtPiece); }else{ getPlayers(1).appendChild(newNoughtPiece); } }else if(piecesToBeSaved[i][j].getPieceColour() == Piece.TicTacToePieceColour.CROSS){ Element newCrossPiece; if(Game.getPlayer(1).getColour().equals(Piece.TicTacToePieceColour.NOUGHT)){ newCrossPiece = getDoc().createElement("piece1"); }else{ newCrossPiece = getDoc().createElement("piece2"); } Element x = getDoc().createElement("x"); x.appendChild(getDoc().createTextNode(i + "")); Element y = getDoc().createElement("y"); y.appendChild(getDoc().createTextNode(j + "")); newCrossPiece.appendChild(x); newCrossPiece.appendChild(y); if(Game.getPlayer(1).getColour().equals(Piece.TicTacToePieceColour.NOUGHT)){ getPlayers(0).appendChild(newCrossPiece); }else{ getPlayers(1).appendChild(newCrossPiece); } }else{} } } }
8
private boolean enteredViaVertex0( int anEdgeIndex) { if (anEdgeIndex < 1 || anEdgeIndex > 5) throw new IllegalArgumentException( "Edge index must be in range [1..5], was " + anEdgeIndex); else { boolean retval; Edge cur = myEdge[anEdgeIndex]; Edge prev = myEdge[anEdgeIndex-1]; retval = (cur == prev.getEdge1Plus() && cur.getVertex0().equals( prev.getVertex1())) || (cur == prev.getEdge0Plus() && cur.getVertex0().equals( prev.getVertex0())); return retval; } }
5
public GayBerneConfigure() { super(new BorderLayout()); if (rotateCursor1 == null) { rotateCursor1 = UserAction.createCursor("images/cursors/rotate1.gif", new Point(16, 17), "rotate"); rotateCursor2 = UserAction.createCursor("images/cursors/rotate2.gif", new Point(14, 11), "rotate"); rotateCursor3 = UserAction.createCursor("images/cursors/rotate3.gif", new Point(16, 17), "rotate"); } ellipsePanel = new EllipsePanel(); JPanel panel = new JPanel(new BorderLayout()); panel.add(ellipsePanel, BorderLayout.CENTER); panel.setBorder(BorderFactory.createTitledBorder("Geometric Anisotropy")); JPanel p = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0)); p.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); ButtonGroup bg = new ButtonGroup(); Dimension dim = ModelerUtilities.getSystemToolBarButtonSize(); AbstractButton rb = new JToggleButton(IconPool.getIcon("resize")); rb.setToolTipText("Resize the particle"); rb.setPreferredSize(dim); rb.setHorizontalAlignment(SwingConstants.CENTER); rb.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { ellipsePanel.setState(EllipsePanel.RESIZE); ellipsePanel.repaint(); } }); rb.setSelected(true); p.add(rb); bg.add(rb); rb = new JToggleButton(new ImageIcon(getClass().getResource("images/Rotate.gif"))); rb.setToolTipText("Assign an initial angle"); rb.setPreferredSize(dim); rb.setHorizontalAlignment(SwingConstants.CENTER); rb.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { ellipsePanel.setState(EllipsePanel.ROTATE); ellipsePanel.repaint(); } }); p.add(rb); bg.add(rb); colorComboBox = new ColorComboBox(this); colorComboBox.setName(GB_COLOR); colorComboBox.setPreferredSize(new Dimension(100, dim.height)); colorComboBox.setSelectedIndex(2); colorComboBox.updateColor(new Runnable() { public void run() { color = colorComboBox.getMoreColor(); ellipsePanel.repaint(); } }); colorComboBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String actionName = colorComboBox.getName(); int id = 0; if (actionName.equals(GB_COLOR)) { id = ((Integer) colorComboBox.getSelectedItem()).intValue(); } if (id == 6 || id == 100) { color = colorComboBox.getMoreColor(); } else { color = ColorRectangle.COLORS[id]; } ellipsePanel.repaint(); } }); p.add(colorComboBox); panel.add(p, BorderLayout.NORTH); add(panel, BorderLayout.NORTH); eAnisotropy = new JLabel("<html>&#949;<sub>e</sub>/&#949;<sub>s</sub></html>", SwingConstants.CENTER); slider1 = new JSlider(JSlider.HORIZONTAL, -10, 10, 0); slider1.setPreferredSize(new Dimension(100, 50)); slider1.setMajorTickSpacing(5); slider1.setMinorTickSpacing(5); slider1.setPaintTicks(true); slider1.setPaintTrack(true); slider1.setPaintLabels(true); slider1.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { JSlider source = (JSlider) e.getSource(); if (!source.getValueIsAdjusting()) { eeVsEs = source.getValue(); if (eeVsEs < 1.0 && eeVsEs > -1.0) eeVsEs = 1.0; eeVsEs = eeVsEs > 0 ? eeVsEs : -1.0 / eeVsEs; eAnisotropy.setText("<html>&#949;<sub>e</sub>/&#949;<sub>s</sub> = " + scientificFormat.format(eeVsEs) + "</html>"); } } }); Hashtable<Integer, JLabel> tableOfLabels = new Hashtable<Integer, JLabel>(); JLabel label = new JLabel("10.0"); label.setFont(littleFont); tableOfLabels.put(10, label); label = new JLabel("5.0"); label.setFont(littleFont); tableOfLabels.put(5, label); label = new JLabel("1.0"); label.setFont(littleFont); tableOfLabels.put(0, label); label = new JLabel("0.2"); label.setFont(littleFont); tableOfLabels.put(-5, label); label = new JLabel("0.1"); label.setFont(littleFont); tableOfLabels.put(-10, label); slider1.setLabelTable(tableOfLabels); panel = new JPanel(new BorderLayout(0, 20)); panel.add(slider1, BorderLayout.NORTH); scientificFormat.applyPattern("##.###"); eAnisotropy.setText("<html>&#949;<sub>e</sub>/&#949;<sub>s</sub> = " + scientificFormat.format((float) eeVsEs) + "</html>"); eAnisotropy.setBorder(BorderFactory.createTitledBorder("Slider Value")); panel.add(eAnisotropy, BorderLayout.CENTER); p = new JPanel(new BorderLayout()); p.setBorder(BorderFactory.createTitledBorder("Energetic Anisotropic Ratio")); p.add(panel, BorderLayout.EAST); label = new JLabel(new ImageIcon(getClass().getResource("images/EnergyAnisotropy.gif"))); label.setBorder(BorderFactory.createLoweredBevelBorder()); p.add(label, BorderLayout.WEST); add(p, BorderLayout.CENTER); panel = new JPanel(new BorderLayout(10, 10)); panel.setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 10)); scientificFormat.applyPattern("#.###"); epsilon0_label = new JLabel("<html>&#949;<sub>0</sub> = " + scientificFormat.format(epsilon0) + "</html>"); epsilon0_label.setBorder(BorderFactory.createTitledBorder("Value")); panel.add(epsilon0_label, BorderLayout.EAST); slider2 = new JSlider(JSlider.HORIZONTAL, 0, 50, 10); slider2.setBorder(BorderFactory.createTitledBorder("Potential Well Depth")); slider2.setMajorTickSpacing(10); slider2.setMinorTickSpacing(5); slider2.setPaintTicks(true); slider2.setPaintTrack(true); slider2.setPaintLabels(true); tableOfLabels = new Hashtable<Integer, JLabel>(); label = new JLabel("0.1 eV"); label.setFont(littleFont); tableOfLabels.put(50, label); label = new JLabel("0.05 eV"); label.setFont(littleFont); tableOfLabels.put(25, label); label = new JLabel("0 eV"); label.setFont(littleFont); tableOfLabels.put(0, label); slider2.setLabelTable(tableOfLabels); slider2.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { JSlider source = (JSlider) e.getSource(); if (!source.getValueIsAdjusting()) { epsilon0 = source.getValue() * 0.002; epsilon0_label.setText("<html>&#949;<sub>0</sub> = " + scientificFormat.format(epsilon0) + "</html>"); } } }); panel.add(slider2, BorderLayout.CENTER); add(panel, BorderLayout.SOUTH); }
9
protected PingResult pingLeft(){ for (int i = this.posX; i >= 0; i--){ if (i == enemyPosX && this.posY == enemyPosY) { return new PingResult(this.posX - i - 1, true); } else if (BattleBotsGUI.instance.obstacles[i][this.posY]) { return new PingResult(this.posX - i - 1, false); } else if (i == 0) { return new PingResult(this.posX, false); } } return null; }
5
public CmdCreateExecutor(SimpleQueues plugin) { this.plugin = plugin; }
0
@Test public void testSetFood() { System.out.println("setFood"); int food = 0; Cell instance = new Cell(0,0); instance.setFood(food); int expResult = 0; int result = instance.getFood(); assertEquals(expResult, result); }
0
public void add(GUITreeComponent comp) { reg.put(comp.getGUITreeComponentID(), comp); }
0
private String parseRes(String res) { Pattern pattern = Pattern.compile(Constant.MESSAGE_PATTER); Matcher matcher = pattern.matcher(res); if (matcher.find()) { return matcher.group().split(":")[1]; } if (res.matches(Constant.ORDER_SUCCESS_REGEX)) { String content = ""; pattern = Pattern.compile(Constant.ORDER_TRAIN_DATE_PATTERN); matcher = pattern.matcher(res); if (matcher.find()) { content = "恭喜预定到了票,时间:" + matcher.group().split("\":")[1]; } pattern = Pattern.compile(Constant.ORDER_TRAIN_FROM); matcher = pattern.matcher(res); if(matcher.find()){ content+= (",从:"+matcher.group().split("\":")[1]); } pattern = Pattern.compile(Constant.ORDER_TRAIN_TO); matcher = pattern.matcher(res); if(matcher.find()){ content+= ("--到:"+matcher.group().split("\":")[1]); } return content; } return "其他"; }
5
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub JSONObject jb = new JSONObject(); String userId = request.getParameter("userId"); try{ connection = new Mongo(); scheduleDB = connection.getDB("schedule"); groupCollection = scheduleDB.getCollection("group_" + userId); DBCursor cur = groupCollection.find(); JSONArray ja = new JSONArray(); while(cur.hasNext()){ //ja.add(cur.next()); JSONObject groupJSONObject= new JSONObject(); DBObject dbo = cur.next(); String id = dbo.get("_id").toString(); String groupName = (String)dbo.get("groupName"); groupJSONObject.put("_id", id); groupJSONObject.put("groupName", groupName); ja.add(groupJSONObject); } jb.put("result", Primitive.ACCEPT); jb.put("groupList",ja); }catch(MongoException e){ jb.put("result", Primitive.DBCONNECTIONERROR); e.printStackTrace(); } PrintWriter writer = response.getWriter(); writer.write(jb.toString()); writer.flush(); writer.close(); }
2
@Override public double getXRotation() { double lowest = 9001; double highest = 0; int y = 0; if (getRotationAngle() == 180) y = -20; if (getRotationAngle() == 360) y = 20; for (Block block : blockArray) { if (block.getXValue() > highest) highest = block.getXValue(); if (block.getXValue() < lowest) lowest = block.getXValue(); } return ((highest + lowest) / 2) + y; }
5
@Override public void add(double score) { if ((score < 0) || (score > 1)) throw new RuntimeException("p-value out of range: " + score); scores.add(score); }
2
@Override public void keyReleased(KeyEvent e) { switch (e.getKeyCode()) { case KeyEvent.VK_W: keys[0] = false; break; case KeyEvent.VK_S: keys[1] = false; break; case KeyEvent.VK_I: keys[2] = false; break; case KeyEvent.VK_K: keys[3] = false; break; default: break; } }
4