Newest questions tagged java - Stack Overflow © stackoverflow.commost recent 30 from stackoverflow.com2018-02-18T00:51:15Zhttp://stackoverflow.com.mevn.net/feeds/tag?tagnames=java&sort=newesthttp://www.creativecommons.org/licenses/by-sa/3.0/rdf http://stackoverflow.com.mevn.net/q/488473910JTextArea not updating across panels/class © stackoverflow.comt.metcalfehttp://stackoverflow.com.mevn.net/users/89256292018-02-18T00:48:40Z2018-02-18T00:48:40Z<p><a href="https://i.stack.imgur.com/dq5lq.png" rel="nofollow noreferrer">Why doesn't the "getTextBody" send back user input from JTextArea when called from another class (the button to trigger is on a another panel), but if i place a button with actionListener in this panel it works and updates everytime. </a></p>http://stackoverflow.com.mevn.net/q/488473800How to make an outbound call in Twilio with Java, using TwiML and not a URL? © stackoverflow.comDaryl Bennetthttp://stackoverflow.com.mevn.net/users/20838542018-02-18T00:46:25Z2018-02-18T00:46:25Z<p>I'm looking to make an outbound call in a Java application using Twilio. All of the tutorials I found used a static TwiML file hosted on a URL. I haven't been able to find any documentation on how to pass in TwiML as a parameter for an outgoing call.</p><p>I found this on this link, but it doesn't explain how to dynamically render TwiML: <a href="https://www.twilio.com/docs/guides/how-to-make-outbound-phone-calls-in-java#where-to-next" rel="nofollow noreferrer">https://www.twilio.com/docs/guides/how-to-make-outbound-phone-calls-in-java#where-to-next</a></p><blockquote><p>Of course, the TwiML you use to make the outbound call doesn't need to be a static file like in this example. Server-side Java code that you control can dynamically render TwiML to use for the outbound call.</p></blockquote><p>I've tried the following:</p><pre><code>PhoneNumber to=new PhoneNumber(toPhone); // Replace with your phone numberPhoneNumber from=new PhoneNumber(fromPhone); // Replace with a Twilio numberTwiML twiml=new VoiceResponse.Builder().say(new Say.Builder(message).build()).build();Call call=Call.creator(to, from, twiml.toXml()).create(client);</code></pre><p>While the <code>Call.creator()</code>has some overloaded methods of <code>(PhoneNumber, PhoneNumber, String)</code>, none of them will accept TwiML, nor XML. </p><p>How do make an outbound call in Java using TwiML?Thanks</p>http://stackoverflow.com.mevn.net/q/48847368-5Java- Extend a class which Extends another class © stackoverflow.comrahulchawlahttp://stackoverflow.com.mevn.net/users/93752192018-02-18T00:44:47Z2018-02-18T00:48:51Z<p>Is this legal in java - I do not get any IDE errorsI have a class</p><pre><code>public farm extends residential {</code></pre><p>and</p><pre><code>public residential extends properties {</code></pre>http://stackoverflow.com.mevn.net/q/488473520Drawing a curve in Java using mouse drag © stackoverflow.comSarthak Sachdevahttp://stackoverflow.com.mevn.net/users/81009202018-02-18T00:42:06Z2018-02-18T00:46:56Z<p>I am new to java and I am trying to draw a curve. The functionality I am trying to implement is that the curves should be defined by a mouse drag followed by a mouse click. Once the drag action is done, I want a line to be drawn from the start of the drag to the end. Clicking on the canvas after that should be considered the third point necessary to define the curve and the line drawn should be changed into a curve.<br>How do I do that?I've gone through different posts here about how to draw Bezier curves but I am super confused. Here's a chunk of my code to draw rectangles, ovals and lines using mouse events:</p><pre><code> public void mousePressed(MouseEvent e) {xCoordinateInitial=e.getX(); //Initialize x-coordinate to the mouse x-coordinateyCoordinateInitial=e.getY() + shiftInY; //Initialize y-coordinate to the mouse y-coordinateSystem.out.println("X-coordinate: " + xCoordinateInitial);System.out.println("Y-coordinate: " + yCoordinateInitial);}public void mouseReleased(MouseEvent e) {Graphics2D G=(Graphics2D) getGraphics();G.setStroke(new BasicStroke(lineThickness));G.setColor(colorSelected);G.setPaint(colorSelected);xCoordinateFinal=e.getX(); //Set final x-coordinate to the mouse x-coordinate after dragyCoordinateFinal=e.getY() + shiftInY; //Set final y-coordinate to the mouse y-coordinate after dragint x=xCoordinateInitial;int y=yCoordinateInitial;int width=xCoordinateFinal - xCoordinateInitial; //Setting widthint height=yCoordinateFinal - yCoordinateInitial; //Setting heightif (yCoordinateFinal &lt; yCoordinateInitial) {y=yCoordinateFinal;height=yCoordinateInitial - yCoordinateFinal;}if (xCoordinateFinal &lt; xCoordinateInitial) {x=xCoordinateFinal;width=xCoordinateInitial - xCoordinateFinal;}// Shape Selectionswitch (shapeSelected) {case Line:G.drawLine(xCoordinateInitial, yCoordinateInitial, xCoordinateFinal, yCoordinateFinal);break;case Rectangle:G.fillRect(x, y, width, height);break;case Oval:G.fillOval(x, y, width, height);break;case Curve :// To implement}}});</code></pre><p>I tried to understand the following but I couldn't make it work:</p><pre><code> Path2D p=new GeneralPath();p.moveTo(x1, y1);p.curveTo(bx1, by1, bx2, by2, x2, y2);G.draw(p);</code></pre>http://stackoverflow.com.mevn.net/q/488473480try with resources only prints once © stackoverflow.comneilnmhttp://stackoverflow.com.mevn.net/users/30677012018-02-18T00:41:11Z2018-02-18T00:41:11Z<p>I have 5 records in <code>pList</code> in the ArrayList below but why does it only print the last record to file ? </p><p>I put the <code>try</code> first and the <code>for</code> loop inside it and that worked but trying to understand the logic why doesn't the code below work ?</p><pre><code>for(Person p: pList){try(PrintWriter pw=new PrintWriter(new BufferedWriter(new FileWriter("persons.txt")))){pw.println(p.toString());}catch(IOException ex){System.out.println(ex.getMessage());}}</code></pre>http://stackoverflow.com.mevn.net/q/48847333-2android studio won't create content.xml file © stackoverflow.comZ10987654321Xhttp://stackoverflow.com.mevn.net/users/63126552018-02-18T00:38:39Z2018-02-18T00:38:39Z<p>I am using android studio 3.0.1.</p><p>As of this update, I can no longer create a new activity and also have it create the content_(name).xml file anymore. It only creates the Java class and the activity_(name).xml file. It doesn't matter if I create a basic, blank, or empty activity. This never happened before. Why is this happening and how can I fix it?</p>http://stackoverflow.com.mevn.net/q/488473220im having trouble creating a login dialog. i want a dialog box to pop up when you click on the login button © stackoverflow.comDanielhttp://stackoverflow.com.mevn.net/users/93752182018-02-18T00:37:03Z2018-02-18T00:37:03Z<p>this is the main class</p><pre><code>import java.awt.event.*;import javax.swing.*;import javax.swing.JPanel;public class Password {public static void main(String[] args) {final JFrame frame=new JFrame("Password Field");JLabel lblUser=new JLabel("User Name:");JTextField tfUser=new JTextField(20);lblUser.setLabelFor(tfUser);JLabel lblPassword=new JLabel("Password:");final JPasswordField pfPassword=new JPasswordField(20);lblPassword.setLabelFor(pfPassword);JButton btnLogin=new JButton("Login");btnLogin.addActionListener( new ActionListener() {public void actionPerformed(ActionEvent e) {String password=new String(pfPassword.getPassword());if(password=="milkyoreos201") {} }});JButton btnGet=new JButton("Display Password");btnGet.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {String password=new String(pfPassword.getPassword());JOptionPane.showMessageDialog(frame,"Password is " + password);}});JPanel panel=new JPanel();panel.setLayout(new SpringLayout());panel.add(lblUser);panel.add(tfUser);panel.add(lblPassword);panel.add(pfPassword);panel.add(btnLogin);panel.add(btnGet);SpringUtilities.makeCompactGrid(panel,3, 2, //rows, cols6, 6, //initX, initY6, 6); //xPad, yPadframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setSize(300, 120);frame.getContentPane().add(panel);frame.setVisible(true);}}</code></pre><p>and this is the other class</p><pre><code>import javax.swing.*;import javax.swing.SpringLayout;import java.awt.*;public class SpringUtilities {public static void printSizes(Component c) {System.out.println("minimumSize=" + c.getMinimumSize());System.out.println("preferredSize=" + c.getPreferredSize());System.out.println("maximumSize=" + c.getMaximumSize());}public static void makeGrid(Container parent,int rows, int cols,int initialX, int initialY,int xPad, int yPad) {SpringLayout layout;try {layout=(SpringLayout)parent.getLayout();} catch (ClassCastException exc) {System.err.println("The first argument to makeGrid must use SpringLayout.");return;}Spring xPadSpring=Spring.constant(xPad);Spring yPadSpring=Spring.constant(yPad);Spring initialXSpring=Spring.constant(initialX);Spring initialYSpring=Spring.constant(initialY);int max=rows * cols;Spring maxWidthSpring=layout.getConstraints(parent.getComponent(0)).getWidth();Spring maxHeightSpring=layout.getConstraints(parent.getComponent(0)).getWidth();for (int i=1; i &lt; max; i++) {SpringLayout.Constraints cons=layout.getConstraints(parent.getComponent(i));maxWidthSpring=Spring.max(maxWidthSpring, cons.getWidth());maxHeightSpring=Spring.max(maxHeightSpring, cons.getHeight());}for (int i=0; i &lt; max; i++) {SpringLayout.Constraints cons=layout.getConstraints(parent.getComponent(i));cons.setWidth(maxWidthSpring);cons.setHeight(maxHeightSpring);}SpringLayout.Constraints lastCons=null;SpringLayout.Constraints lastRowCons=null;for (int i=0; i &lt; max; i++) {SpringLayout.Constraints cons=layout.getConstraints(parent.getComponent(i)); if (i % cols==0) { lastRowCons=lastCons;cons.setX(initialXSpring);} else { cons.setX(Spring.sum(lastCons.getConstraint(SpringLayout.EAST),xPadSpring));}if (i / cols==0) {cons.setY(initialYSpring);} else {cons.setY(Spring.sum(lastRowCons.getConstraint(SpringLayout.SOUTH),yPadSpring));}lastCons=cons;}SpringLayout.Constraints pCons=layout.getConstraints(parent);pCons.setConstraint(SpringLayout.SOUTH,Spring.sum(Spring.constant(yPad),lastCons.getConstraint(SpringLayout.SOUTH)));pCons.setConstraint(SpringLayout.EAST,Spring.sum(Spring.constant(xPad),lastCons.getConstraint(SpringLayout.EAST)));}private static SpringLayout.Constraints getConstraintsForCell(int row, int col,Container parent,int cols) {SpringLayout layout=(SpringLayout) parent.getLayout();Component c=parent.getComponent(row * cols + col);return layout.getConstraints(c);}public static void makeCompactGrid(Container parent,int rows, int cols,int initialX, int initialY,int xPad, int yPad) {SpringLayout layout;try {layout=(SpringLayout)parent.getLayout();} catch (ClassCastException exc) {System.err.println("The first argument to makeCompactGrid must use SpringLayout.");return;}Spring x=Spring.constant(initialX);for (int c=0; c &lt; cols; c++) {Spring width=Spring.constant(0);for (int r=0; r &lt; rows; r++) {width=Spring.max(width,getConstraintsForCell(r, c, parent, cols).getWidth());}for (int r=0; r &lt; rows; r++) {SpringLayout.Constraints constraints=getConstraintsForCell(r, c, parent, cols);constraints.setX(x);constraints.setWidth(width);}x=Spring.sum(x, Spring.sum(width, Spring.constant(xPad)));}Spring y=Spring.constant(initialY);for (int r=0; r &lt; rows; r++) {Spring height=Spring.constant(0);for (int c=0; c &lt; cols; c++) {height=Spring.max(height,getConstraintsForCell(r, c, parent, cols).getHeight());}for (int c=0; c &lt; cols; c++) {SpringLayout.Constraints constraints=getConstraintsForCell(r, c, parent, cols);constraints.setY(y);constraints.setHeight(height);}y=Spring.sum(y, Spring.sum(height, Spring.constant(yPad)));}SpringLayout.Constraints pCons=layout.getConstraints(parent);pCons.setConstraint(SpringLayout.SOUTH, y);pCons.setConstraint(SpringLayout.EAST, x);}}</code></pre><p>this is my first time building a password gui, so sorry if i did a bunch of stuff incorrectly. i want this program to open up a dialog box, telling you info. when you type in the correct user name and password. i have everything except a specific user name and password, and i tried to make a dialog box, but it wouldn't appear.</p>http://stackoverflow.com.mevn.net/q/48847300-6Why won't my method store the length of each array element into my variable? © stackoverflow.comDamohttp://stackoverflow.com.mevn.net/users/93752032018-02-18T00:32:22Z2018-02-18T00:47:02Z<p>This is in Eclipse. I wrote this code that is supposed to sum each <code>String</code> element within the <code>ArrayList</code> and then return the sum cubed. The problem is that it is returning 0.0 every time the method is run with strings added to it.</p><p>I don't understand why on line 6 the loop is not computing the length of each string element and storing the value to <code>sum1</code>.</p><pre><code>public static double q1(ArrayList&lt;String&gt; input1) {ArrayList&lt;String&gt; array1=new ArrayList&lt;String&gt;();double sum1=0;for (String s1: array1) {sum1 +=s1.length(); //Line 6}return Math.pow(sum1, 3);}</code></pre>http://stackoverflow.com.mevn.net/q/488472930Where can I find non-boxing maps for java? © stackoverflow.commmirwaldthttp://stackoverflow.com.mevn.net/users/20235332018-02-18T00:31:19Z2018-02-18T00:36:38Z<p>I know the collections for primitives of the apache commons primitives project.However I miss maps that avoid boxing at all. Does that exist for java? In which java frameworks are they implemented?</p>http://stackoverflow.com.mevn.net/q/48847280-2loader constraint violation when building Spark SQL Context dynamically © stackoverflow.comMezhttp://stackoverflow.com.mevn.net/users/4801392018-02-18T00:29:00Z2018-02-18T00:29:00Z<p>I am getting the following exception</p><pre><code>Exception in thread "main" java.lang.LinkageError: loader constraint violation: when resolving method "org.apache.spark.sql.types.StructType$.apply(Lscala/collection/Seq;)Lorg/apache/spark/sql/types/StructType;" the class loader (instance of org/apache/spark/util/ChildFirstURLClassLoader) of the current class, com/xxx/xxx/xxx/XXXJob, and the class loader (instance of sun/misc/Launcher$AppClassLoader) for the method's defining class, org/apache/spark/sql/types/StructType$, have different Class objects for the type scala/collection/Seq used in the signature</code></pre><p>When running the following code;</p><pre><code> val fields=ArrayBuffer[StructField]()val fieldsArray=ArrayBuffer[StructField]()val columns=job.columnList.sortBy(x=&gt;x.columnOrder)// Prepare to create data framecolumns.foreach(column=&gt;{print(column.columnName)val newField=new StructField(column.columnName, typeUtilities.convertDataType(column.dataType))fields +=newFieldif(typeUtilities.convertDataType(column.dataType)==StringType &amp;&amp; column.maxChars !=null){// First we are going to allow MAX character length for strings in work table... then afterwards// we will trim extra charsval metadata=new MetadataBuilder().putLong("maxlength",DEFAULT_MAX_CHAR_LENGTH).build()fieldsArray +=new StructField(column.columnName, StringType, metadata=metadata)}else{fieldsArray +=new StructField(column.columnName, StringType)}})// Configure schema, and columns from our own configurationval schema=StructType(fieldsArray)</code></pre><p>The line of code having <code>val schema=StructType(fieldsArray)</code> generates the exception. My scala versions are the following;</p><pre><code>&lt;scala.version&gt;2.11.8&lt;/scala.version&gt;&lt;scala.major.version&gt;2.11&lt;/scala.major.version&gt;</code></pre><p>I have tried to change how I generate the StructType but to no avail. I also tried to change scala version to 2.10.4 having a major of 2.10, however again to no avail. </p><p>Anybody could point or shed some light on what potentially might be the problem?</p>http://stackoverflow.com.mevn.net/q/488472670poolDataSource.getConnection() hangs. Tried using ojdbc6 and ojdbc8 jars © stackoverflow.comPrakash Kumar Singhhttp://stackoverflow.com.mevn.net/users/93752302018-02-18T00:27:05Z2018-02-18T00:41:47Z<p>I am using Oracle 11g XE and java 8. I am developing a desktop application and want to do connection pooling. The application hangs while executing pds.getConnection(); I tried using simple JDBC, that works fine so it's not a network/DB issue. Here is the code I am calling -</p><pre><code>/*** This returns DB connection from the DB Connection Pool* * @return* @throws IOException* @throws SQLException*/public static Connection getConnection() throws IOException, SQLException {if (pds==null) {initConnectionPool();}Connection conn=pds.getConnection();System.out.println("Available connections after checkout: " + pds.getAvailableConnectionsCount());System.out.println("Borrowed connections after checkout: " + pds.getBorrowedConnectionsCount());return conn;}/*** init DB Connection Pool* * @return* @throws IOException* @throws SQLException*/private static void initConnectionPool() throws IOException, SQLException {Properties configProperties=Utils.getConfig();// Get the PoolDataSource for UCPPoolDataSource pds=PoolDataSourceFactory.getPoolDataSource();// Set the connection factory first before all other propertiesSystem.out.println("Class name :" + configProperties.getProperty("CONNECTION_FACTORY_CLASS_NAME"));pds.setConnectionFactoryClassName(configProperties.getProperty("CONNECTION_FACTORY_CLASS_NAME"));System.out.println("DB URL==" + configProperties.getProperty("DB_URL"));pds.setURL(configProperties.getProperty("DB_URL"));System.out.println("DB User==" + configProperties.getProperty("DB_USER"));pds.setUser(configProperties.getProperty("DB_USER"));System.out.println("Password==" + configProperties.getProperty("DB_PSWD"));pds.setPassword(configProperties.getProperty("DB_PSWD"));pds.setConnectionPoolName("JDBC_UCP_POOL");// Default is 0. Set the initial number of connections to be created// when UCP is started.pds.setInitialPoolSize(Integer.parseInt(configProperties.getProperty("INITIAL_POOL_SIZE")));// Default is 0. Set the minimum number of connections// that is maintained by UCP at runtime.pds.setMinPoolSize(Integer.parseInt(configProperties.getProperty("MIN_POOL_SIZE")));// Default is Integer.MAX_VALUE (2147483647). Set the maximum number of// connections allowed on the connection pool.pds.setMaxPoolSize(Integer.parseInt(configProperties.getProperty("MAX_POOL_SIZE")));}/*** Loads the config file and return instance of Properties* * @return Proterties* @throws IOException*/public static Properties getConfig() throws IOException {if (configProps !=null)return configProps;configProps=new Properties();FileInputStream in;in=new FileInputStream("bin/resources/config.properties");configProps.load(in);in.close();return configProps;}</code></pre><p>The properties used are-</p><p>DB_URL=jdbc:oracle:thin:@//localhost:1521/XE</p><p>INITIAL_POOL_SIZE=5</p><p>MIN_POOL_SIZE=5</p><p>MAX_POOL_SIZE=10</p><p>CONNECTION_FACTORY_CLASS_NAME=oracle.jdbc.pool.OracleDataSource</p>http://stackoverflow.com.mevn.net/q/48847255-1Print a binary search tree as a single string © stackoverflow.com009http://stackoverflow.com.mevn.net/users/66213562018-02-18T00:24:42Z2018-02-18T00:24:42Z<p>There's a practice problem that I've been working on that's been confusing me.</p><p>Define a function treeLevelOrder which satisfies the following claim:If Q is a binary search tree of integers, then treeLevelOrder(Q) is the String representation of the contents of Q according to their level in the tree. We get this tree as an example</p><pre><code> 9/ \5 16/ \ / \1 7 12 19</code></pre><p>The value of the expression treeLevelOrder(Q) in this case would be"[9,5,16,1,7,12,19]".</p><p>I've seen similar problems, but they don't follow the same format that I'm looking for, wanting to print by level order or as ordered tuples. Here's some sample code I've been working on:</p><pre><code> private String treeLevelOrder(Node Q){if (Q.left==null &amp;&amp; Q.right==null)return "[" + Q.datum + "]";else if (Q.left==null &amp;&amp; Q.right !=null)return "[" + Q.datum + ", "+Q.right.datum+"]" + treeLevelOrder(Q.right);else if (Q.left !=null &amp;&amp; Q.right==null)return"[" + Q.datum + ", "+Q.left.datum+", *]"+ treeLevelOrder(T.left);elsereturn "[" + Q.datum + ", "+Q.left.datum+", "+Q.right.datum+"]" + treeLevelOrder(Q.left) + treeLevelOrder(Q.right); } </code></pre><p>Any assistance would be helpful.</p>http://stackoverflow.com.mevn.net/q/48847247-1i can't get set location (maps) work on OPPO phone Blocked msg target=android.app.ActivityThread$H © stackoverflow.commohamed nassim harzallahhttp://stackoverflow.com.mevn.net/users/93478952018-02-18T00:23:35Z2018-02-18T00:23:35Z<p>Hello when I try to use the app in virtual device work fine, but not on real device OPPO</p><p>logcat</p><p>02-18 01:03:20.681 27579-27579/com.cog.wasselniC E/GoogleMap: <b>Rue de Kouba</b> <br/> <i>Place Id: Eh5SdWUgZGUgS291YmEsIEFubmFiYSwgQWxnw6lyaWU</i> <br/> Address: Rue de Kouba, Annaba, Algérie <br/> Phone: <br/> Website: null02-18 01:03:20.701 27579-27579/com.cog.wasselniC I/System.out: address 1===>Rue de Kouba02-18 01:03:20.701 27579-27579/com.cog.wasselniC I/System.out: address 2==>Rue de Kouba, Annaba, Algérie02-18 01:03:20.702 27579-27579/com.cog.wasselniC I/System.out: address after parse==>Rue de Kouba, Annaba, Algérie02-18 01:03:20.702 27579-27579/com.cog.wasselniC I/System.out: AddressRue de Kouba, Annaba, Algérie02-18 01:03:23.354 27579-27579/com.cog.wasselniC E/ANR_LOG: >>> msg's executing time is too long02-18 01:03:23.354 27579-27579/com.cog.wasselniC E/ANR_LOG: Blocked msg={ when=-2s680ms what=108 target=android.app.ActivityThread$H obj=ResultData{token=android.os.BinderProxy@3fa9186e results[ResultInfo{who=null, request=1, result=-1, data=Intent { (has extras) }}]} } , cost=2680 ms02-18 01:03:23.354 27579-27579/com.cog.wasselniC E/ANR_LOG: >>>Current msg List is:02-18 01:03:23.354 27579-27579/com.cog.wasselniC E/ANR_LOG: Current msg &lt;1>={ when=-2s680ms what=107 target=android.app.ActivityThread$H obj=android.os.BinderProxy@3fa9186e }02-18 01:03:23.354 27579-27579/com.cog.wasselniC E/ANR_LOG: Current msg &lt;2>={ when=-2s666ms what=4 target=android.view.ViewRootImpl$ViewRootHandler obj=com.android.internal.os.SomeArgs@3e552ebe }02-18 01:03:23.354 27579-27579/com.cog.wasselniC E/ANR_LOG: Current msg &lt;3>={ when=-2s664ms what=6 target=android.view.ViewRootImpl$ViewRootHandler arg1=1 arg2=1 }02-18 01:03:23.354 27579-27579/com.cog.wasselniC E/ANR_LOG: Current msg &lt;4>={ when=-2s653ms barrier=40 }02-18 01:03:23.354 27579-27579/com.cog.wasselniC E/ANR_LOG: Current msg &lt;5>={ when=-1s26ms what=0 target=android.os.Handler callback=com.google.maps.api.android.lib6.impl.ew }02-18 01:03:23.355 27579-27579/com.cog.wasselniC E/ANR_LOG: Current msg &lt;6>={ when=-123ms what=1 target=com.google.android.gms.internal.zzaaz$zza obj=com.google.android.gms.internal.zzart$zzb$1@2376fb1f }02-18 01:03:23.355 27579-27579/com.cog.wasselniC E/ANR_LOG: >>>CURRENT MSG DUMP OVER&lt;&lt;&lt;02-18 01:03:23.357 27579-27690/com.cog.wasselniC D/mali_winsys: new_window_surface returns 0x3000</p>http://stackoverflow.com.mevn.net/q/48847239-1My application crashes when I hit login with out entering password/email, I have tried some things in this code but no luck.? © stackoverflow.comuser8501534http://stackoverflow.com.mevn.net/users/85015342018-02-18T00:22:23Z2018-02-18T00:22:23Z<p><a href="https://i.stack.imgur.com/1lvPc.png" rel="nofollow noreferrer">Can anyone help me how to put checks in this code, Thanks/Can anyone help me how to put checks in this code, Thanks/Can anyone help me how to put checks in this code, Thanks</a></p><pre><code>private void loginUser(final String email, final String password) {auth.signInWithEmailAndPassword(email,password).addOnCompleteListener(this, new OnCompleteListener&lt;AuthResult&gt;() {@Overridepublic void onComplete(@NonNull Task&lt;AuthResult&gt; task) {if(!task.isSuccessful()){if(password.length() &lt; 6){Snackbar snackBar=Snackbar.make(activity_main,"Password length must be over 6",Snackbar.LENGTH_SHORT);snackBar.show();}}else{startActivity(new Intent(MainActivity.this,DashBoard.class));}}});</code></pre>http://stackoverflow.com.mevn.net/q/48847135-4How to underline a word in a file there is or not the word © stackoverflow.comAhmed Hegazyhttp://stackoverflow.com.mevn.net/users/78070232018-02-18T00:03:27Z2018-02-18T00:03:27Z<p>I want to make an application such as word<br>when user type any word search it in file<br>if it exists ok<br>if it doesn't exist underline it </p>http://stackoverflow.com.mevn.net/q/48847087-1Is this bad practice for passing an input file in Java? © stackoverflow.comteddymvhttp://stackoverflow.com.mevn.net/users/75711112018-02-17T23:54:51Z2018-02-18T00:49:53Z<p>I have a main class that expects an input file name to be provided through the command line argument; if this is not true then the program exits with an error message.</p><p>We are assuming the existence of a class called SudokuReducer. After making sure there is an input file, the main function will pass the input file (not just the name of the file) to an instance of SudokuReducer.</p><p>What I want to know, is this bad form/practice? Is it wrong to put the entirety of the scan inside a try/catch like this? Because then if I wanted to declare the SudokuReducer instance in 'main' outside of the try/catch instead of in, I can't since it doesn't recognize what 'fileInput' has been passed due to its limited scope inside the 'try'</p><p>Is there a better way of doing this? Here's what I have:</p><pre><code>import java.io.File;public class MainMV {File inputFile;public static void main(String args[]) {// check if file is entered and handle exceptiontry {if (args.length &gt; 0) {File inputFile=new File(args[0]);System.out.println("Processing file");SudokuReducer reducer=new SudokuReducer(inputFile);} else {System.out.println("No file entered.");System.exit(1);}} catch (Exception e) {System.out.println("File failed to open.");System.exit(1);}}</code></pre><p>}</p>http://stackoverflow.com.mevn.net/q/488470830need some assistance with 2d arraylists © stackoverflow.comRShinhttp://stackoverflow.com.mevn.net/users/93751952018-02-17T23:54:15Z2018-02-17T23:54:15Z<p>This is the problem</p><p>Class registration is an important aspect to the college students. When registering for a course, you must know the course reference number (CRN). Based on the CRN, there are a number of details that one can identify, such as a course title. Consider the table below which identifies some CRNs and their associated course title. Each course has a maximum enrollment of 30.</p><p>CRN | COURSE TITLE 12451 | Introduction to IT Problem Solving Using Computer Programming15349 | Object-Oriented Techniques for IT Problem Solving 18467 | Applied IT Programming16890 | Database Fundamentals 13334 | Database Programming</p><p>Create a program for use by the Registrar (user) to enroll students into these courses. A single enrollment into a course occurs when the user enters a CRN. Until the Registrar (user) has indicated they are finished entering CRNs, continue to prompt the user to enter a CRN. You must validate the CRN, providing an error message and re-prompting the user if an invalid CRN is entered. Keep track of the number of enrollments for each course. Course enrollments for a specific CRN cannot exceed its maximum enrollment, or else an error message will appear and the enrollment will not be processed.Once the user has indicated they are finished entering CRNs, display a well-formatted report containing a list of each course with its CRN and title, the number of students enrolled and the number of seats remaining.</p><pre><code>import java.io.IOException;import java.util.ArrayList;import java.util.Scanner;class TwoD{private static boolean typeInt(String a) throws IOException {try {Integer.parseInt(a);return true;} catch (NumberFormatException e) {return false;}}public static void main(String[] args) throws IOException {{System.out.println("These are the courses that you can choose for the students to enroll. \n 12451 | Introduction to IT Problem Solving Using Computer Programming \n 15349 | Object-Oriented Techniques for IT Problem Solving \n 18467 | Applied IT Programming \n 16890 | Database Fundamentals \n 13334 | Database Programming");ArrayList&lt;String&gt; name=new ArrayList&lt;String&gt;();Scanner scan=new Scanner(System.in);System.out.print("What is your student's name? "); String student=scan.next();String a;while(!student.equalsIgnoreCase("quit")) {name.add(student); //after a cycle of while, ask user whether he or she would quit and print the arraylist of students.System.out.print("What is your student's name? ");student=scan.next();}ArrayList&lt; ArrayList&lt;String&gt; &gt; main=new ArrayList&lt; ArrayList&lt;String&gt; &gt;();for(int i=0; i&lt;name.size(); i++){ArrayList&lt;String&gt; course=new ArrayList&lt;String&gt;();for (int j=0; j &lt; name.size(); j++){System.out.print("The course the student is currently enrolling is : ");a=scan.next();while (!a.equalsIgnoreCase("quit")){while(!typeInt(a) || Integer.parseInt(a) !=12451 &amp;&amp; Integer.parseInt(a) !=15349 &amp;&amp; Integer.parseInt(a) !=16890 &amp;&amp; Integer.parseInt(a) !=13334 &amp;&amp; Integer.parseInt(a) !=18467) {System.out.println("Check the courses again."); a=scan.next();}course.add(a);if (a.equalsIgnoreCase("quit")!=true){System.out.print("The course the student is currently enrolling is : ");a=scan.next();}else break;}}main.add(course);}for(int i=0; i &lt; name.size(); i++){System.out.print("Name " + i + ": ");for(int j=0; j &lt; main.get(i).size(); j++){System.out.print(main.get(i).get(j) + " ");}System.out.println();}}}}</code></pre><p>After running the code, 1. the quit doesn't do anything for a first couple of times2. I still haven't figured out how to ignore overlapping inputs3. I need to set the limits up to 30</p><p>can anyone help?</p>http://stackoverflow.com.mevn.net/q/48847002-2cannot find symbol length (Java) © stackoverflow.comSebastjanhttp://stackoverflow.com.mevn.net/users/92459052018-02-17T23:39:28Z2018-02-17T23:47:11Z<p>Given an array of numbers, I have to return the number of times that 9 appears in the array. I created a new array, where I added all the 9s from the original array. But at the end when I want to return the length of the new array, I get an error "cannot find symbol length".I know that in this case, length is an attribute, not a method, so that's not the problem. I even used the length attribute in the for loop and it doesn't seem to be a problem (because the error occurs at line 8). This is starting to become frustrating. If anyone knows what the reason for this is, please let me know.</p><pre><code>public int arrayCount9(int[] nums) {ArrayList&lt;Integer&gt; array=new ArrayList&lt;Integer&gt;();for (int i=0; i &lt; nums.length; i++){if (nums[i]==9){array.add(nums[i]);}}int len=array.length;return len;}</code></pre>http://stackoverflow.com.mevn.net/q/488469980I am trying to add collision detection to this particle system I made © stackoverflow.comJake Wintershttp://stackoverflow.com.mevn.net/users/81320472018-02-17T23:39:04Z2018-02-17T23:39:04Z<p>I am doing this in processing which is essentially java and I have never attempted anything like this before. Can't find any examples of collision detection using arrays to map the pixels. </p><p>I am not really trying to make them realistic collisions. I was thinking it would have the same response as if it hit a wall which is just for it to change directions in whatever axis is appropriate for the wall it hit. </p><p>I have tried checking if the x and y position are the same but can't seem to make that work. I'd appreciate any input on this.</p><pre><code>import java.util.Arrays;int numOfParticles=10;float[] x=new float[numOfParticles]; //initial position of y only mattersfloat[] px=new float[numOfParticles];float[] y=new float[numOfParticles]; float[] py=new float[numOfParticles];int speed=10;//inversly related to speedfloat[] xIncrement=new float[numOfParticles]; //the ratio of increments determines the patternfloat[] yIncrement=new float[numOfParticles]; // it is the slope of the line//float xIncrement=10/speed; //the ratio of increments determines the pattern//float yIncrement=11/speed; // it is the slope of the linecolor currentColor;int alpha=100;//range of 0-255//radius of ballint radius=1;//thickness of line behind ballint thickness=5;int rateOfColor=5; //this is inversely related to rate but also changes the range of colorsint maxColor=255;int minColor=0;void setup(){size(500,500);background(0);colorMode(HSB);strokeWeight(thickness);frameRate(60);//initialize particlesfor(int i=0;i&lt;numOfParticles;i++){xIncrement[i]=random(0,100)/speed; //the ratio of increments determines the patternyIncrement[i]=random(0,100)/speed; // it is the slope of the linex[i]=random(0,width);px[i]=x[i];y[i]=random(0,height);py[i]=y[i];}//you can either initialize all of them individually or do a random one//x[0]=0;//px[0]=x[0];//y[0]=450;//py[0]=y[0];//x[1]=width;//px[1]=x[1];//y[1]=450;//py[1]=y[1];}void draw(){ background(0); //comment out for criss crossfor(int i=0; i &lt; numOfParticles; i++){particle(i);}}void particle(int particleNum){currentColor=color(minColor + (x[particleNum]/rateOfColor)%maxColor,255,255,alpha);stroke(currentColor);fill(currentColor);ellipse(x[particleNum],y[particleNum],radius,radius);line(px[particleNum],py[particleNum],x[particleNum],y[particleNum]);px[particleNum]=x[particleNum];py[particleNum]=y[particleNum];y[particleNum]+=yIncrement[particleNum];x[particleNum]+=xIncrement[particleNum];if(x[particleNum] &gt; width + 1 || x[particleNum] &lt; 0){x[particleNum] -=2*xIncrement[particleNum];xIncrement[particleNum]*=-1;}if( y[particleNum] &gt; height + 1 || y[particleNum] &lt; 0){y[particleNum] -=2*yIncrement[particleNum];yIncrement[particleNum]*=-1;}//if(Arrays.binarySearch(x,x[particleNum]) &gt;=0 &amp;&amp; Arrays.binarySearch(y,y[particleNum]) &gt;=0){// xIncrement[particleNum]*=-1;// yIncrement[particleNum]*=-1;// print("*\n");// stop();//} print("x[0]=" + x[0] + "\n");print("x[1]=" + x[1] + "\n");print("y[0]=" + y[0] + "\n");print("y[1]=" + y[1] + "\n");}</code></pre>http://stackoverflow.com.mevn.net/q/488469940How do I return rows with a specific value first and rest all the values of a table in a Alphabetic order © stackoverflow.comDinesh Raohttp://stackoverflow.com.mevn.net/users/77578602018-02-17T23:38:39Z2018-02-17T23:52:22Z<p>I need to get <code>book_name</code> and <code>book_code</code> order <code>by book_name</code> in alphabetic order.</p><p>Input to my query is <strong>Author_code</strong>.</p><p>I have three tables:</p><p><strong>Table1</strong>: </p><pre><code>Books (Independent Table which will have all the books)</code></pre><p><strong>Table2</strong>: </p><pre><code>Authors (Independent Table which will have all the authors)</code></pre><p><strong>Table3</strong>: </p><pre><code>Author_Books(This table will provide the information about which book is which author's primary book. **Note**: One Author can have many books) </code></pre><ol><li><p>If I pass Author_code I need to get the primary book of that Author as first row one and rest all books in a table should come order by book_name in alphabetic</p></li><li><p>If I don't pass any input to my query I need all the book's in alphabetic order. </p></li></ol><p><strong>My query return's author's default book:</strong></p><pre><code>SELECT book_CD, book_NAM from books where Alpha_NUM_book_CD=(SELECT Alpha_NUM_book_CD from Author_BookJOIN Author on Author.NUM_Author_CD=Author_Book.NUM_Author_CD where Author.NUM_Author_CD=(SELECT NUM_Author_CD from Author where ALPHA_3_Author_CD='') AND Author_Book.PRIM_book_SW='Y');</code></pre><p><strong>Result</strong>: </p><p>This returns Default book of a Author.</p><p><strong>How to write a query which satisfy both my cases</strong> </p><p>We are using Oracle 11g.</p>http://stackoverflow.com.mevn.net/q/488469810Sending a POST request in libGDX © stackoverflow.comFragrhttp://stackoverflow.com.mevn.net/users/87392702018-02-17T23:37:29Z2018-02-17T23:37:29Z<p>How would I go about sending a POST request using libGDX in order to act as if I was logging in?</p><p>When I use Postman to send a POST request to my server using IP:8080/login?email=EMAIL&amp;password=12345. It shows the HTML code for the correct page after you login. However when using the below code in libGDX it gives me the main login page. I've tried using setContent with and without the ?. I've tried using a Map that contains email and password and passing that into the setContent with HttpParametersUtils.convertHttpParameters(), but no luck.</p><p>I also read a post in regards to sending a POST request with Java that requires you to open the connection first before passing in the parameters. But if this the case I have no idea how to go about it using libGDXs networking methods.</p><p>This is currently what I have. </p><pre><code> String URL="http://IP:8080/login";Net.HttpRequest httpPOST=new Net.HttpRequest(Net.HttpMethods.POST);httpPOST.setUrl(URL);httpPOST.setContent("?email=EMAIL&amp;password=12345");Gdx.net.sendHttpRequest(httpPOST, new Net.HttpResponseListener() {@Overridepublic void handleHttpResponse(Net.HttpResponse httpResponse) {Gdx.app.log("MSG", httpResponse.getResultAsString());}@Overridepublic void failed(Throwable t) {Gdx.app.log("LOGIN", "was NOT successful!");}@Overridepublic void cancelled() {Gdx.app.log("LOGIN", "was cancelled!");}});</code></pre>http://stackoverflow.com.mevn.net/q/488469480How can i can freeze credit held by another account in Stellar SDK? © stackoverflow.comyouneshttp://stackoverflow.com.mevn.net/users/93267942018-02-17T23:30:50Z2018-02-17T23:30:50Z<p>Anyone is familiar with Stellar.org?please i need help . i read the guide of them but still i couldn't find a solution .this is the guide<a href="https://www.stellar.org/developers/guides/issuing-assets.html" rel="nofollow noreferrer">https://www.stellar.org/developers/guides/issuing-assets.html</a><a href="https://www.stellar.org/developers/guides/concepts/assets.html#revoking-access" rel="nofollow noreferrer">https://www.stellar.org/developers/guides/concepts/assets.html#revoking-access</a></p><p>in their guide it says that as an anchor i can freeze credit held by another account .i set the AUTHORIZATION REVOCABLE to true . but still i searched and i couldn't find how to freeze a specifice account credit</p><p>this was the code in stellar guide</p><pre><code>import org.stellar.sdk.AccountFlag;Network.useTestNetwork();Server server=new Server("https://horizon-testnet.stellar.org");// Keys for issuing accountKeyPair issuingKeys=KeyPair.fromSecretSeed("SCZANGBA5YHTNYVVV4C3U252E2B6P6F5T3U6MM63WBSBZATAQI3EBTQ4");AccountResponse sourceAccount=server.accounts().account(issuingKeys);Transaction setAuthorization=new Transaction.Builder(sourceAccount).addOperation(new SetOptionsOperation.Builder().setSetFlags(AccountFlag.AUTH_REQUIRED_FLAG.getValue() |AccountFlag.AUTH_REVOCABLE_FLAG.getValue()).build()).build();setAuthorization.sign(issuingKeys);server.submitTransaction(setAuthorization); </code></pre>http://stackoverflow.com.mevn.net/q/48846933-1Making item lottery based on chances and item ids from table © stackoverflow.comForgetshttp://stackoverflow.com.mevn.net/users/93734392018-02-17T23:28:26Z2018-02-18T00:09:39Z<p>I'm trying to figure out how to select a random item with it's own given chance from a table of values like this:</p><pre><code>itemlottery (npcid, item, chance) VALUES (9100100, 1402011, 167)itemlottery (npcid, item, chance) VALUES (9100100, 1041082, 267)itemlottery (npcid, item, chance) VALUES (9100100, 1322003, 1668)itemlottery (npcid, item, chance) VALUES (9100100, 1061033, 89)itemlottery (npcid, item, chance) VALUES (9100100, 1051001, 89)itemlottery (npcid, item, chance) VALUES (9100100, 2000005, 188983)</code></pre><p>Those are the values that I need (the list actually contains more than 50+ items).</p><p>Now my question is how can I read these values then generate a random item based on those chances in Java?</p><p>This is for a game NPC, what would give players a random lottery item based on the chances.</p><p>You HAVE to get one item and you can't get multiple items. the higher the chance, the more likely it is to get that item.</p><pre><code>public int itemId, chance, npcid;private static final Logger LOG=Logger.getLogger(ItemLottery.class.getName());public ItemLottery(int itemId, int chance) {this.itemId=itemId;this.chance=chance;}protected void loadItemLottery(int npcid) {final List&lt;itemlottery&gt; ret=new LinkedList&lt;&gt;();Connection con=null;PreparedStatement ps=null;ResultSet rs=null;String query="SELECT * FROM `ItemLottery` WHERE `npcid`=?";try {con=DatabaseManager.getConnection();ps=con.prepareStatement(query);ps.setInt(1, npcid); rs=ps.executeQuery();while (rs.next())ret.add( new ItemLottery(rs.getInt("item"), rs.getInt("prob")));} catch (SQLException e) {LOG.log(Level.WARNING, "Could not read ItemLottery data for item " + npcid, e);} finally {DatabaseManager.cleanup(rs, ps, con);}}</code></pre><p>So this should load the lottery from the table of sql values? Now how do I actually set the function up to preform the action I'm looking for.</p><p>It should randomize the itemid and obtain an item based on that chance after loading from the db. </p>http://stackoverflow.com.mevn.net/q/48846902-1Spring Special Beans © stackoverflow.comPrakashhttp://stackoverflow.com.mevn.net/users/18921412018-02-17T23:23:06Z2018-02-18T00:11:00Z<p>Can we declare a special spring bean which can be instantiated before spring checks for the Spring Profiles declarations?The challenge is to set the active spring profile from a spring bean , but it seems spring looks for declared profiles and then goes for bean instantiation.</p><p>I have this weird requirement because I need to set the active profile but cannot use -Dspring.profiles.active=profilename.So, I need to do it in code by using System.setProperty().Also, I cannot use any SpringContextListener because it is not a web application.</p>http://stackoverflow.com.mevn.net/q/488468550Filtering RecycleView incorrect display of results © stackoverflow.comVictor Yezhovhttp://stackoverflow.com.mevn.net/users/93534402018-02-17T23:15:31Z2018-02-17T23:27:46Z<h2>Discription:</h2><p>I have an android app, and in one of parts of it user can choose his skills, like tags in <a href="https://stackoverflow.com">https://stackoverflow.com</a></p><p><a href="https://i.stack.imgur.com/z88kQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/z88kQ.png" alt="enter image description here"></a></p><p>So when user taps on plus button, he can see all available skills and choose what he wants <a href="https://i.stack.imgur.com/F8Iwf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/F8Iwf.png" alt="enter image description here"></a></p><p>As you see there is a filter in the top of the screen, to find skills that user wants to add. And here comes the problem, and it has many impacts</p><p>For example if i type "Eng" to find "English", the result will be "Spanish"<a href="https://i.stack.imgur.com/4FnkA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4FnkA.png" alt="enter image description here"></a></p><p>Do not hurry to tell me, that the problem is in filtring algorithm, becausemy console logs, say, that result is correct, and filter find only "English"What is more if i choose this option, the correct answer "English" is displayed under the "Spanish"<a href="https://i.stack.imgur.com/d0tYA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/d0tYA.png" alt="enter image description here"></a></p><p>What is more is if a i save changes, in my account is shown that i actually choose "English"<a href="https://i.stack.imgur.com/uhyTs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uhyTs.png" alt="You can see the difference between fist screenshoot and this"></a></p><p>So filtring is correct, and saving data is correct to, the problem is in displaying skills names. Why i call it magic? because console logs right before displaying the result show correct name</p><p>And i noticed that if i will go back to full list of skills it will be wrong displayed too</p><p><a href="https://i.stack.imgur.com/OySYQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OySYQ.png" alt="enter image description here"></a></p><p>But as in previous cases, my console logs says, that all is OK, and i have normal skill list without duplicates</p><p>Here is my code samples : </p><p>search - is simple EditText field</p><pre><code>search.addTextChangedListener(new TextWatcher() {@Overridepublic void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}@Overridepublic void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {chipAdapter.getFilter().filter(charSequence);}@Overridepublic void afterTextChanged(Editable editable) {}});</code></pre><p>Adapter :</p><pre><code>@Overridepublic void onBindViewHolder(final ChipAdapterAllSkills.ChipViewHolder holder, final int position) {String skill=filtredSkillList.get(position).getName();System.err.println("SKILL "+skill+" position "+position);holder.skillChip.setChipText(skill);holder.skillChip.setSelectable(true);holder.skillChip.setSelected(true);holder.skillChip.setTextColor(MainAplication.getContext().getResources().getColor(R.color.accent));holder.skillChip.changeBackgroundColor(MainAplication.getContext().getResources().getColor(R.color.blue));holder.skillChip.setOnSelectClickListener(new OnSelectClickListener() {@Overridepublic void onSelectClick(View v, boolean selected) {System.err.println(selected);if(!selected) {SelectSkills.getSkillsToAdd().add(filtredSkillList.get(position));}else {SelectSkills.getSkillsToAdd().remove(filtredSkillList.get(position));}}});}@Overridepublic int getItemCount() {return filtredSkillList.size();}@Overridepublic Filter getFilter() {return new Filter() {@Overrideprotected FilterResults performFiltering(CharSequence charSequence) {String target=charSequence.toString();if (target.isEmpty()) {filtredSkillList=skillList;} else {List&lt;Skill&gt; list=new ArrayList&lt;&gt;();for (Skill s : skillList) {if (s.getName().toLowerCase().contains(target.toLowerCase())) {list.add(s);System.err.println(s.getName());}}filtredSkillList=list;}FilterResults results=new FilterResults();results.values=filtredSkillList;return results;}@Overrideprotected void publishResults(CharSequence charSequence, FilterResults filterResults) {filtredSkillList=(ArrayList&lt;Skill&gt;) filterResults.values;notifyDataSetChanged();}};}</code></pre><p>I really don`t know what is going on, maybe some of you can help) </p><p>I have suspicions that maybe problem is in threading, but i didn`t do any changes in them in this piece of code</p>http://stackoverflow.com.mevn.net/q/488468280combining null layout with card layout [java] © stackoverflow.comEric mansenhttp://stackoverflow.com.mevn.net/users/73210982018-02-17T23:09:44Z2018-02-17T23:35:12Z<p>I'm trying to combine the cardlayout function with the null layout.However when i try to run the program it doesn't work. The buttons do not appear at the boundries i tell them. Am i doing something wrong or is the whole concept of using them both wrong?</p><pre><code>public class CardLayoutTest extends JFrame {private static final long serialVersionUID=1L;private JPanel cardPanel, jp1, jp2, buttonPanel;private JLabel jl1, jl2;private JButton btn1, btn2;private CardLayout cardLayout=new CardLayout();public CardLayoutTest() {setTitle("Test med CardLayout");setSize(400, 300);Insets insets=getInsets();cardPanel=new JPanel();buttonPanel=new JPanel();cardPanel.setLayout(cardLayout);jp1=new JPanel();jp2=new JPanel();jl1=new JLabel("Card 1");jl2=new JLabel("Card 2");jp1.add(jl1);jp2.add(jl2);cardPanel.add(jp1, "1");cardPanel.add(jp2, "2");btn1=new JButton("Show Card 1");btn1.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {cardLayout.show(cardPanel, "1");}});btn2=new JButton("Show Card 2");btn2.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {cardLayout.show(cardPanel, "2");}});buttonPanel.add(btn1);buttonPanel.add(btn2);add(cardPanel, BorderLayout.NORTH);add(buttonPanel, null);Dimension size1=btn1.getPreferredSize();btn1.setBounds(100 + insets.left, 100 + insets.top,size1.width, size1.height);Dimension size=btn2.getPreferredSize();btn2.setBounds(210 + insets.left, 130 + insets.top,size.width, size.height);}public static void main(String[] args) {EventQueue.invokeLater(new Runnable() {@Overridepublic void run() {CardLayoutTest frame=new CardLayoutTest();frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setVisible(true);}});}</code></pre><p>}</p>http://stackoverflow.com.mevn.net/q/488467930Dequeueing from a generic type queue, null pointer exception? © stackoverflow.comhalo2x2http://stackoverflow.com.mevn.net/users/93667132018-02-17T23:05:28Z2018-02-17T23:54:33Z<p>I am trying to make it dequeue the front node and print it out, however I am getting the following error: </p><p>Exception in thread "main" java.lang.NullPointerException</p><p>at MyQueue.toString(MyQueue.java:25)</p><p>at TestQueue.main(TestQueue.java:13) </p><p>From the TestQueue class, I am expecting the outputs 1 then after dequeueing 1 again, then finally 2 from the second toString call.</p><pre><code>public class TestQueue {public static void main(String[] args) {MyQueue&lt;String&gt; qStr=new MyQueue();qStr.enqueue("1");qStr.enqueue("2");qStr.enqueue("3");qStr.enqueue("4");qStr.enqueue("5");qStr.toString(qStr.front);qStr.dequeue();qStr.toString(qStr.front);}} public class MyQueue&lt;T&gt;{MyNode&lt;T&gt; back;MyNode&lt;T&gt; front;public MyQueue(){back=null;front=null;}public void enqueue(T payload) {if(back==null) {MyNode&lt;T&gt; firstnode=new MyNode&lt;T&gt;(payload);back=firstnode; front=firstnode;}else {MyNode&lt;T&gt; addtoback=new MyNode&lt;T&gt;(payload, back.next, null);back=addtoback;}}public String toString(MyNode&lt;T&gt; x) {System.out.println(x.payload);if(x.payload==null) {return "";}else{return (String) x.payload;}}public void dequeue() {if (isEmpty()) {throw new RuntimeException("Queue underflow");} else if (front==back) {T payload1=front.payload;front=null;back=null;System.out.println(payload1);}T payload1=front.payload;front=front.previous;System.out.println(payload1);}public Boolean isEmpty() {if(back==null) {return true;}return false;}public int size() {MyNode&lt;T&gt; k=back;if(isEmpty()||k.next==null) {return 0;}k=k.next;return 1+size();}</code></pre>http://stackoverflow.com.mevn.net/q/48846774-1How to inject MockMvc in Spring Boot? © stackoverflow.comLeandro Borges Ferreirahttp://stackoverflow.com.mevn.net/users/71015542018-02-17T23:01:45Z2018-02-17T23:28:02Z<p>I am following this tutorial about integration test in Spring Boot: <a href="http://www.baeldung.com/spring-boot-testing" rel="nofollow noreferrer">http://www.baeldung.com/spring-boot-testing</a></p><p>Well, but when I try to Inject MockMvc I always get: </p><blockquote><p>Error creating bean with name 'mockMvcBuilder' defined in class pathresource[org/springframework/boot/test/autoconfigure/web/servlet/MockMvcAutoConfiguration.class]:Bean instantiation via factory method failed; nested exception isorg.springframework.beans.BeanInstantiationException: Failed toinstantiate[org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder]:Factory method 'mockMvcBuilder' threw exception; nested exception isjava.lang.NoClassDefFoundError:org/springframework/web/servlet/DispatcherServlet</p></blockquote><p>My test class is:</p><pre><code>@RunWith(SpringRunner.class)@SpringBootTest(webEnvironment=SpringBootTest.WebEnvironment.RANDOM_PORT,classes=MyApplication.class)@AutoConfigureMockMvcpublic class MyControllerIntegrationTest {@Injectprivate MockMvc mockMvc;//Some code here</code></pre><p>Well, I can see that it can't find the DispatcherServlet, but I'm not sure why is this happening... The test seams to be correct. </p><p>Does anyone knows what I am missing?</p><p>Edit:</p><p>This is the relevant part of my POM:</p><pre><code>&lt;parent&gt;&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;&lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt;&lt;version&gt;2.0.0.RC1&lt;/version&gt;&lt;relativePath/&gt; &lt;!-- lookup parent from repository --&gt;&lt;/parent&gt;&lt;properties&gt;&lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt;&lt;project.reporting.outputEncoding&gt;UTF-8&lt;/project.reporting.outputEncoding&gt;&lt;java.version&gt;1.8&lt;/java.version&gt;&lt;/properties&gt;&lt;dependencies&gt;&lt;dependency&gt;&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;&lt;artifactId&gt;spring-boot-starter-jersey&lt;/artifactId&gt;&lt;/dependency&gt;&lt;dependency&gt;&lt;groupId&gt;com.h2database&lt;/groupId&gt;&lt;artifactId&gt;h2&lt;/artifactId&gt;&lt;scope&gt;runtime&lt;/scope&gt;&lt;/dependency&gt;&lt;dependency&gt;&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;&lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;&lt;scope&gt;test&lt;/scope&gt;&lt;/dependency&gt;&lt;dependency&gt;&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;&lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt;&lt;/dependency&gt;&lt;dependency&gt;&lt;groupId&gt;com.google.code.gson&lt;/groupId&gt;&lt;artifactId&gt;gson&lt;/artifactId&gt;&lt;version&gt;2.8.2&lt;/version&gt;&lt;/dependency&gt;&lt;/dependencies&gt;&lt;build&gt;&lt;plugins&gt;&lt;plugin&gt;&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;&lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;&lt;/plugin&gt;&lt;/plugins&gt;&lt;/build&gt;&lt;repositories&gt;&lt;repository&gt;&lt;id&gt;spring-snapshots&lt;/id&gt;&lt;name&gt;Spring Snapshots&lt;/name&gt;&lt;url&gt;https://repo.spring.io/snapshot&lt;/url&gt;&lt;snapshots&gt;&lt;enabled&gt;true&lt;/enabled&gt;&lt;/snapshots&gt;&lt;/repository&gt;&lt;repository&gt;&lt;id&gt;spring-milestones&lt;/id&gt;&lt;name&gt;Spring Milestones&lt;/name&gt;&lt;url&gt;https://repo.spring.io/milestone&lt;/url&gt;&lt;snapshots&gt;&lt;enabled&gt;false&lt;/enabled&gt;&lt;/snapshots&gt;&lt;/repository&gt;&lt;/repositories&gt;&lt;pluginRepositories&gt;&lt;pluginRepository&gt;&lt;id&gt;spring-snapshots&lt;/id&gt;&lt;name&gt;Spring Snapshots&lt;/name&gt;&lt;url&gt;https://repo.spring.io/snapshot&lt;/url&gt;&lt;snapshots&gt;&lt;enabled&gt;true&lt;/enabled&gt;&lt;/snapshots&gt;&lt;/pluginRepository&gt;&lt;pluginRepository&gt;&lt;id&gt;spring-milestones&lt;/id&gt;&lt;name&gt;Spring Milestones&lt;/name&gt;&lt;url&gt;https://repo.spring.io/milestone&lt;/url&gt;&lt;snapshots&gt;&lt;enabled&gt;false&lt;/enabled&gt;&lt;/snapshots&gt;&lt;/pluginRepository&gt;&lt;/pluginRepositories&gt;</code></pre>http://stackoverflow.com.mevn.net/q/48846771-1Processing serial communication issue © stackoverflow.comClaytronhttp://stackoverflow.com.mevn.net/users/39538762018-02-17T23:01:31Z2018-02-18T00:02:31Z<p>I am using Processing (java) to communicate over serial to an Arduino which controls two servos and a laser. Everything works independently, however when I turn the laser on using Processing I am unable to control the servos until I turn the laser back off.Troubleshooting I've tried:</p><ol><li>Manually sending commands to the Arduino using Arduino Serial orPutty results in thethe Arduino working as expected (servo control isindependent of laser status)</li><li>Putting the Arduino in the serial-bridge configuration to monitor whatserial commands Processing is sending to the Arduino, and it is as expected (motor positions, laser status)</li><li>I am using an external power supply so I know its not amax-current-draw issue. (and it works </li><li>Included delays in Processing, flushing the Arduino buffer.</li><li>Used all "\n", "\r", "\r\n" combinations.</li></ol><p>Here is my processing program :</p><pre><code>import processing.serial.*;import org.gamecontrolplus.gui.*;import org.gamecontrolplus.*;import net.java.games.input.*;String ard_ser="/dev/ttyACM0"; ControlIO control;ControlDevice stick;float px, py;int deg_x, deg_y;boolean trailOn;Serial myPort;ArrayList&lt;PVector&gt; shadows=new ArrayList&lt;PVector&gt;();ArrayList&lt;PVector&gt; trail=new ArrayList&lt;PVector&gt;();public void setup() {size(400, 400);myPort=new Serial(this, Serial.list()[0],9600);printArray(Serial.list());// Initialise the ControlIOcontrol=ControlIO.getInstance(this);// Find a device that matches the configuration filestick=control.getMatchedDevice("joystick");if (stick==null) {println("No suitable device configured");System.exit(-1); // End the program NOW!}// Setup a function to trap events for this buttonstick.getButton("LASER").plug(this, "toggleLaser", ControlIO.ON_PRESS);}// Poll for user input called from the draw() method.public void getUserInput() {px=map(stick.getSlider("X").getValue(), -1, 1, 0, width);deg_x=int(map(stick.getSlider("X").getValue(),-1,1,0,180));py=map(stick.getSlider("Y").getValue(), -1, 1, 0, height);deg_y=int(map(stick.getSlider("Y").getValue(),-1,1,0,180));//stick.getButton("LASER").plug(this,"toggleLaser",ControlIO.);}// Event handler for the Laser buttonpublic void toggleLaser() {println("laser"); if (myPort.available()&gt;0){myPort.write("-1\n");}//delay(1000);return;}public void draw() {getUserInput(); // Pollingbackground(255, 255, 240);// Draw shadowsfill(0, 0, 255, 32);noStroke();for (PVector shadow : shadows)ellipse(shadow.x, shadow.y, shadow.z, shadow.z);if ( trail.size() &gt; 1) {stroke(132, 0, 0);for (int n=1; n &lt; trail.size(); n++) {PVector v0=trail.get(n-1);PVector v1=trail.get(n);line(v0.x, v0.y, v1.x, v1.y);v0=v1;}}// Show positionnoStroke();fill(255, 64, 64, 64);ellipse(px, py, 20, 20);String position=str(deg_x)+','+str(deg_y)+'\n';if (myPort.available()&gt;0){//println(position);myPort.write(position);}delay(10);}</code></pre><p>It has a little visualization to monitor the motor location, and basically just sends "mot_x_pos,mot_y_pos \n", and a "-1\n" to toggle the laser. example output serial stream: </p><pre><code>90,90\n 50,50\n-1\n</code></pre><p>The Arduino code parses the stream and controls the motors/laser:</p><pre><code>#include &lt;Servo.h&gt;bool laser=true; // true sets the value high (off for my transistor)char val=0;const int laser_pin=7;int out1=9; //servo pinsint out2=11;boolean newData=true;Servo servo_x; Servo servo_y;int pos_x=0;int pos_y=0;int x_prev=90;int y_prev=90;void setup() {Serial.begin(9600);Serial.println("&lt;Arduino is ready&gt;");servo_x.attach(out1);servo_y.attach(out2);pinMode(laser_pin, OUTPUT);digitalWrite(laser_pin, laser); //turn laser off on startup}void loop(){while(Serial.available()&gt;0){pos_x=Serial.parseInt();pos_y=Serial.parseInt();val=Serial.read(); // this catches the newline escape charactersif ( (pos_x&lt;0) || (pos_y&lt;0) ){//toggle laserif(laser){laser=false;}else {laser=true;}digitalWrite(laser_pin, laser);}else if( (val=='\n') || (val=='\r') ){if(pos_x !=x_prev){ //only write to the motors if something has changedservo_x.write(pos_x);x_prev=pos_x;}if(pos_y !=y_prev){servo_y.write(pos_y); y_prev=pos_y;} }}}</code></pre><p>Any suggestions would be appreciated, thanks.</p>http://stackoverflow.com.mevn.net/q/488466080hashing with salt wildfly © stackoverflow.comjorehttp://stackoverflow.com.mevn.net/users/90727762018-02-17T22:37:12Z2018-02-17T22:37:12Z<p>I need your help with wildfly and salt password hashing using PBKDF2 module.I get an error in wildfly debug.log like this <code>PB0XX.. Invalid or mispelled module option: hmacAlgorithm</code></p><p>I set up in standalone.xml the value like this <code>hmacAlgorithm=HMacSHA256</code></p><p>I also get an error in log like this <code>Failed to verify password in JAAS callbackhandler other: java.lang.SecurityException InvalidUser</code> but I provide all correct credentials</p><p>Thanks for help!</p>